connect-api-cli 1.1.9 → 1.1.11

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
@@ -40,34 +40,9 @@ function printResult(result) {
40
40
 
41
41
  // src/cli/index.ts
42
42
  var import_commander = require("commander");
43
- var fs9 = __toESM(require("fs"));
43
+ var fs11 = __toESM(require("fs"));
44
44
  var import_path8 = __toESM(require("path"));
45
45
 
46
- // src/core/private-file.ts
47
- var import_fs = __toESM(require("fs"));
48
- function restrictPermissions(fd) {
49
- if (process.platform !== "win32") import_fs.default.fchmodSync(fd, 384);
50
- }
51
- function readPrivateFile(file) {
52
- const fd = import_fs.default.openSync(file, "r");
53
- try {
54
- restrictPermissions(fd);
55
- return import_fs.default.readFileSync(fd, "utf8");
56
- } finally {
57
- import_fs.default.closeSync(fd);
58
- }
59
- }
60
- function writePrivateFile(file, contents) {
61
- const fd = import_fs.default.openSync(file, import_fs.default.constants.O_WRONLY | import_fs.default.constants.O_CREAT, 384);
62
- try {
63
- restrictPermissions(fd);
64
- import_fs.default.ftruncateSync(fd, 0);
65
- import_fs.default.writeFileSync(fd, contents, "utf8");
66
- } finally {
67
- import_fs.default.closeSync(fd);
68
- }
69
- }
70
-
71
46
  // src/services/auth.ts
72
47
  var import_axios = __toESM(require("axios"));
73
48
  var crypto = __toESM(require("crypto"));
@@ -75,9 +50,9 @@ var crypto = __toESM(require("crypto"));
75
50
  // src/config/index.ts
76
51
  var dotenv = __toESM(require("dotenv"));
77
52
  var import_path = __toESM(require("path"));
78
- var import_fs2 = __toESM(require("fs"));
53
+ var import_fs = __toESM(require("fs"));
79
54
  var envPath = import_path.default.resolve(process.cwd(), ".env");
80
- if (import_fs2.default.existsSync(envPath)) {
55
+ if (import_fs.default.existsSync(envPath)) {
81
56
  dotenv.config({ path: envPath, quiet: true });
82
57
  } else {
83
58
  dotenv.config({ quiet: true });
@@ -92,12 +67,12 @@ var DEFAULT_OAUTH = {
92
67
  };
93
68
  function loadServiceAccountCredentials(filePath) {
94
69
  const abs = import_path.default.isAbsolute(filePath) ? filePath : import_path.default.resolve(process.cwd(), filePath);
95
- if (!import_fs2.default.existsSync(abs)) {
70
+ if (!import_fs.default.existsSync(abs)) {
96
71
  throw new Error(`Service Account credentials file not found: ${abs}`);
97
72
  }
98
73
  let raw;
99
74
  try {
100
- raw = JSON.parse(import_fs2.default.readFileSync(abs, "utf8"));
75
+ raw = JSON.parse(import_fs.default.readFileSync(abs, "utf8"));
101
76
  } catch {
102
77
  throw new Error(`Invalid Service Account credentials JSON: ${abs}`);
103
78
  }
@@ -174,6 +149,44 @@ function getConfig(authMode = process.env.AGC_AUTH_MODE ?? "deveco") {
174
149
  }
175
150
 
176
151
  // src/services/auth.ts
152
+ var OAuthRefreshRejectedError = class extends Error {
153
+ constructor(message) {
154
+ super(message);
155
+ this.name = "OAuthRefreshRejectedError";
156
+ }
157
+ };
158
+ function normalizeOAuthToken(data, previousRefreshToken) {
159
+ const raw = data && typeof data === "object" ? data : {};
160
+ const accessToken = pickString(raw, "accessToken", "access_token");
161
+ if (!accessToken) {
162
+ throw new Error("Authentication failed");
163
+ }
164
+ const refreshToken = pickString(raw, "refreshToken", "refresh_token") || previousRefreshToken?.trim() || "";
165
+ return {
166
+ accessToken,
167
+ expireTime: pickExpireSeconds(raw),
168
+ refreshToken: refreshToken || void 0
169
+ };
170
+ }
171
+ function isDefinitiveOAuthRefreshFailure(err) {
172
+ if (err instanceof OAuthRefreshRejectedError) return true;
173
+ const status = err?.response?.status;
174
+ return typeof status === "number" && status >= 400 && status < 500;
175
+ }
176
+ function pickString(raw, ...keys) {
177
+ for (const key of keys) {
178
+ const value = raw[key];
179
+ if (typeof value === "string" && value.trim()) return value.trim();
180
+ }
181
+ return "";
182
+ }
183
+ function pickExpireSeconds(raw) {
184
+ for (const key of ["expireTime", "expiresTime", "expiresIn", "expires_in"]) {
185
+ const value = Number(raw[key]);
186
+ if (Number.isFinite(value) && value > 0) return value;
187
+ }
188
+ return 0;
189
+ }
177
190
  var SA_AUD = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
178
191
  var SA_JWT_TTL_SEC = 3600;
179
192
  var DEVECO_CHECK_URL = process.env.AGC_DEVECO_CHECK_URL || "https://cn.devecostudio.huawei.com/authrouter/auth/api/jwToken/check";
@@ -264,7 +277,8 @@ var AuthService = class {
264
277
  if (!res.data.ret || res.data.ret.code !== 0) {
265
278
  throw new Error(res.data.ret?.msg || "Authentication failed");
266
279
  }
267
- return res.data;
280
+ const token = normalizeOAuthToken(res.data);
281
+ return { ret: res.data.ret, accessToken: token.accessToken, expireTime: token.expireTime, refreshToken: token.refreshToken };
268
282
  } catch (err) {
269
283
  if (err instanceof Error && err.name === "AbortError") {
270
284
  throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
@@ -289,9 +303,15 @@ var AuthService = class {
289
303
  signal: controller.signal
290
304
  });
291
305
  if (!res.data.ret || res.data.ret.code !== 0) {
292
- throw new Error(res.data.ret?.msg || "Refresh failed");
306
+ throw new OAuthRefreshRejectedError(res.data.ret?.msg || "Refresh failed");
293
307
  }
294
- return res.data;
308
+ const token = normalizeOAuthToken(res.data, refreshToken);
309
+ return {
310
+ ret: res.data.ret,
311
+ accessToken: token.accessToken,
312
+ expireTime: token.expireTime,
313
+ refreshToken: token.refreshToken
314
+ };
295
315
  } catch (err) {
296
316
  if (err instanceof Error && err.name === "AbortError") {
297
317
  throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
@@ -348,26 +368,517 @@ function normalizePem(privateKey) {
348
368
 
349
369
  // src/core/oauth-team.ts
350
370
  var import_axios2 = __toESM(require("axios"));
371
+
372
+ // src/core/token-vault.ts
373
+ var crypto2 = __toESM(require("crypto"));
374
+ var import_fs4 = __toESM(require("fs"));
375
+ var import_os2 = __toESM(require("os"));
376
+ var import_path3 = __toESM(require("path"));
377
+
378
+ // src/core/key-store.ts
379
+ var import_child_process = require("child_process");
351
380
  var import_fs3 = __toESM(require("fs"));
352
- var import_path2 = __toESM(require("path"));
353
381
  var import_os = __toESM(require("os"));
354
- var TOKEN_FILE = import_path2.default.join(import_os.default.homedir(), ".connect-api-cli-token.json");
382
+ var import_path2 = __toESM(require("path"));
383
+
384
+ // src/core/private-file.ts
385
+ var import_fs2 = __toESM(require("fs"));
386
+ function restrictPermissions(fd) {
387
+ if (process.platform !== "win32") import_fs2.default.fchmodSync(fd, 384);
388
+ }
389
+ function readPrivateFile(file) {
390
+ const fd = import_fs2.default.openSync(file, "r");
391
+ try {
392
+ restrictPermissions(fd);
393
+ return import_fs2.default.readFileSync(fd, "utf8");
394
+ } finally {
395
+ import_fs2.default.closeSync(fd);
396
+ }
397
+ }
398
+ function writePrivateFile(file, contents) {
399
+ const fd = import_fs2.default.openSync(file, import_fs2.default.constants.O_WRONLY | import_fs2.default.constants.O_CREAT, 384);
400
+ try {
401
+ restrictPermissions(fd);
402
+ import_fs2.default.ftruncateSync(fd, 0);
403
+ import_fs2.default.writeFileSync(fd, contents, "utf8");
404
+ } finally {
405
+ import_fs2.default.closeSync(fd);
406
+ }
407
+ }
408
+
409
+ // src/core/key-store.ts
410
+ var KEYCHAIN_SERVICE = "connect-api-cli";
411
+ var KEYCHAIN_ACCOUNT = "token-key";
412
+ var KEYCHAIN_SLOT = `${KEYCHAIN_SERVICE}\0${KEYCHAIN_ACCOUNT}`;
413
+ var SECRET_SLOT = "connect-api-cli\0token-key";
414
+ var unlocked = /* @__PURE__ */ new Map();
415
+ function tokenKeyPath(tokenFile) {
416
+ return import_path2.default.join(import_path2.default.dirname(tokenFile), ".connect-api-cli-token.key");
417
+ }
418
+ function forgetKeyFile(keyFile) {
419
+ unlocked.delete(cacheId("dpapi", keyFile));
420
+ unlocked.delete(cacheId("file", keyFile));
421
+ }
422
+ function createDefaultKeyStore(tokenFile) {
423
+ if (process.platform === "win32") return createDpapiKeyStore(tokenKeyPath(tokenFile));
424
+ if (process.platform === "darwin") return createKeychainKeyStore();
425
+ return createLinuxKeyStore(tokenKeyPath(tokenFile));
426
+ }
427
+ function keyStoreById(id, tokenFile) {
428
+ const keyFile = tokenKeyPath(tokenFile);
429
+ if (id === "dpapi") return createDpapiKeyStore(keyFile);
430
+ if (id === "keychain") return createKeychainKeyStore();
431
+ if (id === "secret-service") return createSecretServiceKeyStore();
432
+ if (id === "file") return createFileKeyStore(keyFile);
433
+ throw new Error(`Unknown token key protection: ${id}`);
434
+ }
435
+ function createFileKeyStore(keyFile) {
436
+ return {
437
+ id: "file",
438
+ load: () => readPrefixedKey("file", keyFile, "raw:"),
439
+ save: (key) => writePrefixedKey("file", keyFile, "raw:", key),
440
+ clear: () => removePrefixedKey("file", keyFile)
441
+ };
442
+ }
443
+ function createDpapiKeyStore(keyFile) {
444
+ return {
445
+ id: "dpapi",
446
+ load: () => {
447
+ const cached = recall("dpapi", keyFile);
448
+ if (cached) return cached;
449
+ const wrapped = readPrefixed(keyFile, "dpapi:");
450
+ if (!wrapped) return null;
451
+ const key = decodeKey(dpapi("unprotect", wrapped));
452
+ if (!key) return null;
453
+ remember("dpapi", keyFile, key);
454
+ return key;
455
+ },
456
+ save: (key) => {
457
+ assertKey(key);
458
+ writePrefixed(keyFile, "dpapi:", dpapi("protect", key.toString("base64")));
459
+ remember("dpapi", keyFile, key);
460
+ },
461
+ clear: () => removePrefixedKey("dpapi", keyFile)
462
+ };
463
+ }
464
+ function createKeychainKeyStore() {
465
+ return {
466
+ id: "keychain",
467
+ load: () => keychainLoad(),
468
+ save: (key) => keychainSave(key),
469
+ clear: () => keychainClear()
470
+ };
471
+ }
472
+ function createSecretServiceKeyStore() {
473
+ return {
474
+ id: "secret-service",
475
+ load: () => secretLookup(),
476
+ save: (key) => {
477
+ if (!secretStore(key)) {
478
+ throw new Error("Failed to store the token key in the Secret Service.");
479
+ }
480
+ },
481
+ clear: () => secretClear()
482
+ };
483
+ }
484
+ function createLinuxKeyStore(keyFile) {
485
+ const store = {
486
+ id: "file",
487
+ load() {
488
+ if (hasSecretTool()) {
489
+ const key2 = secretLookup();
490
+ if (key2) {
491
+ store.id = "secret-service";
492
+ return key2;
493
+ }
494
+ }
495
+ const key = readPrefixedKey("file", keyFile, "raw:");
496
+ if (key) store.id = "file";
497
+ return key;
498
+ },
499
+ save(key) {
500
+ if (hasSecretTool() && secretStore(key)) {
501
+ store.id = "secret-service";
502
+ removePrefixedKey("file", keyFile);
503
+ return;
504
+ }
505
+ store.id = "file";
506
+ writePrefixedKey("file", keyFile, "raw:", key);
507
+ },
508
+ clear() {
509
+ secretClear();
510
+ removePrefixedKey("file", keyFile);
511
+ }
512
+ };
513
+ return store;
514
+ }
515
+ function cacheId(id, slot) {
516
+ return `${id}\0${slot}`;
517
+ }
518
+ function remember(id, slot, key) {
519
+ unlocked.set(cacheId(id, slot), Buffer.from(key));
520
+ }
521
+ function recall(id, slot) {
522
+ const hit = unlocked.get(cacheId(id, slot));
523
+ return hit ? Buffer.from(hit) : null;
524
+ }
525
+ function forget(id, slot) {
526
+ unlocked.delete(cacheId(id, slot));
527
+ }
528
+ function assertKey(key) {
529
+ if (key.length !== 32) throw new Error("Token key must be 32 bytes");
530
+ }
531
+ function decodeKey(b64) {
532
+ const key = Buffer.from(b64, "base64");
533
+ return key.length === 32 ? key : null;
534
+ }
535
+ function readPrefixed(keyFile, prefix) {
536
+ if (!import_fs3.default.existsSync(keyFile)) return null;
537
+ const text = import_fs3.default.readFileSync(keyFile, "utf8").replace(/^\uFEFF/, "").trim();
538
+ if (!text.startsWith(prefix)) return null;
539
+ return text.slice(prefix.length);
540
+ }
541
+ function readPrefixedKey(id, keyFile, prefix) {
542
+ const cached = recall(id, keyFile);
543
+ if (cached) return cached;
544
+ const b64 = readPrefixed(keyFile, prefix);
545
+ if (!b64) return null;
546
+ const key = decodeKey(b64);
547
+ if (!key) return null;
548
+ remember(id, keyFile, key);
549
+ return key;
550
+ }
551
+ function writePrefixed(keyFile, prefix, payload) {
552
+ import_fs3.default.mkdirSync(import_path2.default.dirname(keyFile), { recursive: true });
553
+ writePrivateFile(keyFile, `${prefix}${payload}
554
+ `);
555
+ }
556
+ function writePrefixedKey(id, keyFile, prefix, key) {
557
+ assertKey(key);
558
+ writePrefixed(keyFile, prefix, key.toString("base64"));
559
+ remember(id, keyFile, key);
560
+ }
561
+ function removePrefixedKey(id, keyFile) {
562
+ forget(id, keyFile);
563
+ import_fs3.default.rmSync(keyFile, { force: true });
564
+ }
565
+ var DPAPI_SCRIPT = `
566
+ $ErrorActionPreference = 'Stop'
567
+ Add-Type -AssemblyName System.Security
568
+ $utf8 = New-Object System.Text.UTF8Encoding $false
569
+ $b64 = [System.IO.File]::ReadAllText($env:CONNECT_API_SECRET_IN).Trim()
570
+ $bytes = [System.Convert]::FromBase64String($b64)
571
+ $entropy = [System.Text.Encoding]::UTF8.GetBytes('connect-api-cli-token-v1')
572
+ $scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
573
+ if ($env:CONNECT_API_SECRET_OP -eq 'protect') {
574
+ $outBytes = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope)
575
+ } elseif ($env:CONNECT_API_SECRET_OP -eq 'unprotect') {
576
+ $outBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope)
577
+ } else {
578
+ throw 'bad op'
579
+ }
580
+ [System.IO.File]::WriteAllText($env:CONNECT_API_SECRET_OUT, [System.Convert]::ToBase64String($outBytes), $utf8)
581
+ `;
582
+ function powershellExe() {
583
+ const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
584
+ const candidate = import_path2.default.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
585
+ return import_fs3.default.existsSync(candidate) ? candidate : "powershell.exe";
586
+ }
587
+ function dpapi(op, payloadB64) {
588
+ const dir = import_fs3.default.mkdtempSync(import_path2.default.join(import_os.default.tmpdir(), "connect-api-cli-"));
589
+ const inPath = import_path2.default.join(dir, "in.txt");
590
+ const outPath = import_path2.default.join(dir, "out.txt");
591
+ try {
592
+ import_fs3.default.writeFileSync(inPath, payloadB64, { encoding: "utf8", mode: 384 });
593
+ const encoded = Buffer.from(DPAPI_SCRIPT, "utf16le").toString("base64");
594
+ try {
595
+ (0, import_child_process.execFileSync)(powershellExe(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
596
+ env: {
597
+ ...process.env,
598
+ CONNECT_API_SECRET_IN: inPath,
599
+ CONNECT_API_SECRET_OUT: outPath,
600
+ CONNECT_API_SECRET_OP: op
601
+ },
602
+ windowsHide: true,
603
+ timeout: 2e4,
604
+ stdio: ["ignore", "pipe", "pipe"],
605
+ encoding: "utf8"
606
+ });
607
+ } catch (e) {
608
+ const stderr = typeof e.stderr === "string" ? e.stderr.trim().slice(0, 400) : "";
609
+ throw new Error(`Windows DPAPI ${op} failed${stderr ? `: ${stderr}` : ""}`);
610
+ }
611
+ if (!import_fs3.default.existsSync(outPath)) throw new Error(`Windows DPAPI ${op} failed: no output`);
612
+ return import_fs3.default.readFileSync(outPath, "utf8").replace(/^\uFEFF/, "").trim();
613
+ } finally {
614
+ import_fs3.default.rmSync(dir, { recursive: true, force: true });
615
+ }
616
+ }
617
+ function keychainLoad() {
618
+ const cached = recall("keychain", KEYCHAIN_SLOT);
619
+ if (cached) return cached;
620
+ try {
621
+ const out = (0, import_child_process.execFileSync)("security", [
622
+ "find-generic-password",
623
+ "-s",
624
+ KEYCHAIN_SERVICE,
625
+ "-a",
626
+ KEYCHAIN_ACCOUNT,
627
+ "-w"
628
+ ], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
629
+ const key = decodeKey(out.trim());
630
+ if (!key) return null;
631
+ remember("keychain", KEYCHAIN_SLOT, key);
632
+ return key;
633
+ } catch (e) {
634
+ const status = e.status;
635
+ if (status === 44) return null;
636
+ throw new Error("macOS Keychain read failed");
637
+ }
638
+ }
639
+ function keychainSave(key) {
640
+ assertKey(key);
641
+ (0, import_child_process.execFileSync)("security", [
642
+ "add-generic-password",
643
+ "-U",
644
+ "-A",
645
+ "-s",
646
+ KEYCHAIN_SERVICE,
647
+ "-a",
648
+ KEYCHAIN_ACCOUNT,
649
+ "-w",
650
+ key.toString("base64")
651
+ ], { timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
652
+ remember("keychain", KEYCHAIN_SLOT, key);
653
+ }
654
+ function keychainClear() {
655
+ forget("keychain", KEYCHAIN_SLOT);
656
+ try {
657
+ (0, import_child_process.execFileSync)("security", [
658
+ "delete-generic-password",
659
+ "-s",
660
+ KEYCHAIN_SERVICE,
661
+ "-a",
662
+ KEYCHAIN_ACCOUNT
663
+ ], { timeout: 1e4, stdio: "ignore" });
664
+ } catch {
665
+ }
666
+ }
667
+ var secretToolAvailable;
668
+ function hasSecretTool() {
669
+ if (process.platform === "win32" || process.platform === "darwin") return false;
670
+ if (secretToolAvailable !== void 0) return secretToolAvailable;
671
+ const r = (0, import_child_process.spawnSync)("secret-tool", ["--version"], { stdio: "ignore" });
672
+ const missing = !!r.error && r.error.code === "ENOENT";
673
+ secretToolAvailable = !missing;
674
+ return secretToolAvailable;
675
+ }
676
+ function secretLookup() {
677
+ const cached = recall("secret-service", SECRET_SLOT);
678
+ if (cached) return cached;
679
+ const r = (0, import_child_process.spawnSync)("secret-tool", [
680
+ "lookup",
681
+ "service",
682
+ "connect-api-cli",
683
+ "username",
684
+ "token-key"
685
+ ], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
686
+ if (r.error || r.status !== 0) return null;
687
+ const key = decodeKey((r.stdout || "").trim());
688
+ if (!key) return null;
689
+ remember("secret-service", SECRET_SLOT, key);
690
+ return key;
691
+ }
692
+ function secretStore(key) {
693
+ assertKey(key);
694
+ const r = (0, import_child_process.spawnSync)("secret-tool", [
695
+ "store",
696
+ "--label=connect-api-cli token key",
697
+ "service",
698
+ "connect-api-cli",
699
+ "username",
700
+ "token-key"
701
+ ], {
702
+ input: key.toString("base64"),
703
+ encoding: "utf8",
704
+ timeout: 1e4,
705
+ stdio: ["pipe", "pipe", "pipe"]
706
+ });
707
+ if (r.status !== 0) return false;
708
+ remember("secret-service", SECRET_SLOT, key);
709
+ return true;
710
+ }
711
+ function secretClear() {
712
+ forget("secret-service", SECRET_SLOT);
713
+ (0, import_child_process.spawnSync)("secret-tool", [
714
+ "clear",
715
+ "service",
716
+ "connect-api-cli",
717
+ "username",
718
+ "token-key"
719
+ ], { stdio: "ignore", timeout: 1e4 });
720
+ }
721
+
722
+ // src/core/token-vault.ts
723
+ var KTY = "connect-api-cli-secret";
724
+ var TokenDecryptError = class extends Error {
725
+ constructor() {
726
+ super("Token cache authentication failed");
727
+ this.name = "TokenDecryptError";
728
+ }
729
+ };
730
+ function tokenFilePath() {
731
+ return import_path3.default.join(import_os2.default.homedir(), ".connect-api-cli-token.json");
732
+ }
733
+ function readVault(file, store) {
734
+ if (!import_fs4.default.existsSync(file)) return null;
735
+ let parsed;
736
+ try {
737
+ parsed = JSON.parse(readPrivateFile(file));
738
+ } catch {
739
+ return null;
740
+ }
741
+ if (isLegacyToken(parsed)) {
742
+ writeVault(file, parsed, store);
743
+ return parsed;
744
+ }
745
+ if (!isEnvelope(parsed)) return null;
746
+ const keys = store ?? storeForWrap(parsed.wrap, file);
747
+ if (!keys) return null;
748
+ const key = keys.load();
749
+ if (!key) return null;
750
+ try {
751
+ return JSON.parse(decryptJson(parsed, key));
752
+ } catch (e) {
753
+ if (e instanceof TokenDecryptError) return null;
754
+ throw e;
755
+ }
756
+ }
757
+ function writeVault(file, value, store) {
758
+ const keys = store ?? storeForWrite(file);
759
+ let key = keys.load();
760
+ if (!key) {
761
+ key = crypto2.randomBytes(32);
762
+ keys.save(key);
763
+ }
764
+ const envelope = {
765
+ kty: KTY,
766
+ v: 1,
767
+ alg: "A256GCM",
768
+ wrap: keys.id,
769
+ ...encryptJson(JSON.stringify(value), key)
770
+ };
771
+ atomicWrite(file, `${JSON.stringify(envelope, null, 2)}
772
+ `);
773
+ }
774
+ function clearVault(file) {
775
+ const wrap = peekWrap(file);
776
+ let existed = import_fs4.default.existsSync(file);
777
+ import_fs4.default.rmSync(file, { force: true });
778
+ if (wrap) {
779
+ try {
780
+ keyStoreById(wrap, file).clear();
781
+ } catch {
782
+ }
783
+ }
784
+ const keyFile = tokenKeyPath(file);
785
+ if (import_fs4.default.existsSync(keyFile)) {
786
+ import_fs4.default.rmSync(keyFile, { force: true });
787
+ existed = true;
788
+ }
789
+ forgetKeyFile(keyFile);
790
+ return existed;
791
+ }
792
+ function storeForWrite(file) {
793
+ const wrap = peekWrap(file);
794
+ if (wrap) {
795
+ const existing = storeForWrap(wrap, file);
796
+ if (existing?.load()) return existing;
797
+ }
798
+ return createDefaultKeyStore(file);
799
+ }
800
+ function storeForWrap(wrap, file) {
801
+ try {
802
+ return keyStoreById(wrap, file);
803
+ } catch {
804
+ return null;
805
+ }
806
+ }
807
+ function peekWrap(file) {
808
+ if (!import_fs4.default.existsSync(file)) return null;
809
+ try {
810
+ const parsed = JSON.parse(readPrivateFile(file));
811
+ if (parsed?.kty === KTY && typeof parsed.wrap === "string") return parsed.wrap;
812
+ } catch {
813
+ return null;
814
+ }
815
+ return null;
816
+ }
817
+ function isLegacyToken(value) {
818
+ if (!value || typeof value !== "object") return false;
819
+ const rec = value;
820
+ return typeof rec.accessToken === "string" && rec.kty !== KTY;
821
+ }
822
+ function isEnvelope(value) {
823
+ if (!value || typeof value !== "object") return false;
824
+ const v = value;
825
+ return v.kty === KTY && v.v === 1 && v.alg === "A256GCM" && typeof v.wrap === "string" && typeof v.iv === "string" && typeof v.tag === "string" && typeof v.ct === "string";
826
+ }
827
+ function encryptJson(plain, key) {
828
+ const iv = crypto2.randomBytes(12);
829
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
830
+ const ct = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
831
+ return {
832
+ iv: iv.toString("base64"),
833
+ tag: cipher.getAuthTag().toString("base64"),
834
+ ct: ct.toString("base64")
835
+ };
836
+ }
837
+ function decryptJson(env, key) {
838
+ try {
839
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
840
+ decipher.setAuthTag(Buffer.from(env.tag, "base64"));
841
+ return Buffer.concat([
842
+ decipher.update(Buffer.from(env.ct, "base64")),
843
+ decipher.final()
844
+ ]).toString("utf8");
845
+ } catch {
846
+ throw new TokenDecryptError();
847
+ }
848
+ }
849
+ function atomicWrite(file, contents) {
850
+ const tmp = `${file}.${process.pid}.tmp`;
851
+ try {
852
+ writePrivateFile(tmp, contents);
853
+ try {
854
+ if (import_fs4.default.existsSync(file)) import_fs4.default.unlinkSync(file);
855
+ import_fs4.default.renameSync(tmp, file);
856
+ } catch {
857
+ writePrivateFile(file, contents);
858
+ import_fs4.default.rmSync(tmp, { force: true });
859
+ }
860
+ } catch (e) {
861
+ import_fs4.default.rmSync(tmp, { force: true });
862
+ throw e;
863
+ }
864
+ }
865
+
866
+ // src/core/oauth-team.ts
355
867
  var cachedTeamId;
356
868
  function readPersistedTeamId() {
357
869
  try {
358
- if (!import_fs3.default.existsSync(TOKEN_FILE)) return void 0;
359
- const data = JSON.parse(readPrivateFile(TOKEN_FILE));
360
- return data.teamId || void 0;
870
+ const data = readVault(tokenFilePath());
871
+ return data?.teamId || void 0;
361
872
  } catch {
362
873
  return void 0;
363
874
  }
364
875
  }
365
876
  function writePersistedTeamId(teamId) {
366
877
  try {
367
- if (!import_fs3.default.existsSync(TOKEN_FILE)) return;
368
- const data = JSON.parse(readPrivateFile(TOKEN_FILE));
878
+ const data = readVault(tokenFilePath());
879
+ if (!data) return;
369
880
  data.teamId = teamId;
370
- writePrivateFile(TOKEN_FILE, JSON.stringify(data, null, 2));
881
+ writeVault(tokenFilePath(), data);
371
882
  } catch {
372
883
  }
373
884
  }
@@ -375,8 +886,8 @@ async function resolveOAuthTeamId(cfg, accessToken) {
375
886
  if (cfg.teamId) {
376
887
  return cfg.teamId;
377
888
  }
378
- if (cachedTeamId !== void 0) {
379
- return cachedTeamId || void 0;
889
+ if (cachedTeamId) {
890
+ return cachedTeamId;
380
891
  }
381
892
  const persisted = readPersistedTeamId();
382
893
  if (persisted) {
@@ -394,26 +905,18 @@ async function resolveOAuthTeamId(cfg, accessToken) {
394
905
  maxRedirects: 0
395
906
  }
396
907
  );
397
- const teams = res.data.teams || [];
398
908
  if (res.data.ret && res.data.ret.code !== 0) {
399
909
  throw new Error(
400
910
  `Failed to list teams for OAuth teamId: ${res.data.ret.msg || JSON.stringify(res.data.ret)}`
401
911
  );
402
912
  }
403
- if (teams.length === 0) {
404
- cachedTeamId = null;
913
+ const firstTeam = res.data.teams?.[0];
914
+ if (!firstTeam?.id) {
405
915
  throw new Error("OAuth account has no teams. Cannot set teamId for API calls.");
406
916
  }
407
- if (teams.length === 1) {
408
- cachedTeamId = teams[0].id;
409
- writePersistedTeamId(cachedTeamId);
410
- return cachedTeamId;
411
- }
412
- cachedTeamId = null;
413
- const preview = teams.slice(0, 8).map((t) => `${t.id}${t.name ? `(${t.name})` : ""}`).join(", ");
414
- throw new Error(
415
- `Multiple teams found (${teams.length}). Set AGC_TEAM_ID to one of: ${preview}`
416
- );
917
+ cachedTeamId = firstTeam.id;
918
+ writePersistedTeamId(cachedTeamId);
919
+ return cachedTeamId;
417
920
  }
418
921
  function getCachedOAuthTeamId() {
419
922
  if (cachedTeamId) return cachedTeamId;
@@ -425,9 +928,9 @@ function clearOAuthTeamIdCache() {
425
928
 
426
929
  // src/core/deveco-token.ts
427
930
  var import_crypto = require("crypto");
428
- var import_fs4 = require("fs");
429
- var import_os2 = require("os");
430
- var import_path3 = require("path");
931
+ var import_fs5 = require("fs");
932
+ var import_os3 = require("os");
933
+ var import_path4 = require("path");
431
934
  var ALGORITHM = "aes-256-gcm";
432
935
  var KEY_LENGTH = 32;
433
936
  var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
@@ -441,11 +944,11 @@ function decryptAesGcm(ciphertext, key, iv, authTag) {
441
944
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
442
945
  }
443
946
  function readJson(filePath) {
444
- return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
947
+ return JSON.parse((0, import_fs5.readFileSync)(filePath, "utf8"));
445
948
  }
446
949
  function requireFile(filePath, label) {
447
950
  try {
448
- return (0, import_fs4.readFileSync)(filePath);
951
+ return (0, import_fs5.readFileSync)(filePath);
449
952
  } catch (err) {
450
953
  const code = err.code;
451
954
  if (code === "ENOENT") {
@@ -461,8 +964,8 @@ function loadKek(kekId, keysDir) {
461
964
  if (!KEK_VERSIONS.includes(kekId)) {
462
965
  throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
463
966
  }
464
- const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
465
- const keysDirBase = (0, import_path3.resolve)(keysDir);
967
+ const rootKeyPath = (0, import_path4.resolve)((0, import_path4.join)(keysDir, `${kekId}.bin`));
968
+ const keysDirBase = (0, import_path4.resolve)(keysDir);
466
969
  if (!rootKeyPath.startsWith(keysDirBase)) {
467
970
  throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
468
971
  }
@@ -473,16 +976,16 @@ function loadKek(kekId, keysDir) {
473
976
  return kek;
474
977
  }
475
978
  function decryptToken(tokenDir, keysDir) {
476
- const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
979
+ const blob = readJson((0, import_path4.join)(tokenDir, "token.enc"));
477
980
  if (blob.algorithm !== ALGORITHM) {
478
981
  throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
479
982
  }
480
983
  if (!blob.ciphertext || !blob.iv || !blob.authTag) {
481
- throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.enc")}`);
984
+ throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.enc")}`);
482
985
  }
483
- const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
986
+ const wrapped = readJson((0, import_path4.join)(tokenDir, "token.dek"));
484
987
  if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
485
- throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.dek")}`);
988
+ throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.dek")}`);
486
989
  }
487
990
  const kek = loadKek(wrapped.kekId, keysDir);
488
991
  const dek = decryptAesGcm(
@@ -524,10 +1027,10 @@ function extractJwt(plaintext) {
524
1027
  return { jwt };
525
1028
  }
526
1029
  function configHome() {
527
- return process.env.XDG_CONFIG_HOME || (0, import_path3.join)((0, import_os2.homedir)(), ".config");
1030
+ return process.env.XDG_CONFIG_HOME || (0, import_path4.join)((0, import_os3.homedir)(), ".config");
528
1031
  }
529
1032
  function candidatesFor(source) {
530
- const home = (0, import_os2.homedir)();
1033
+ const home = (0, import_os3.homedir)();
531
1034
  if (CLI_SOURCE_ALIASES.includes(source)) {
532
1035
  if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
533
1036
  return candidatesFor("deveco-code").map((c) => ({
@@ -539,8 +1042,8 @@ function candidatesFor(source) {
539
1042
  return [
540
1043
  {
541
1044
  source,
542
- tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
543
- keysDir: (0, import_path3.join)(home, ".local", "share", "deveco-cli", "keys"),
1045
+ tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path4.join)(home, ".config", "deveco-cli"),
1046
+ keysDir: (0, import_path4.join)(home, ".local", "share", "deveco-cli", "keys"),
544
1047
  via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
545
1048
  }
546
1049
  ];
@@ -548,31 +1051,31 @@ function candidatesFor(source) {
548
1051
  const appName = SOURCE_APP_NAMES[source];
549
1052
  const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
550
1053
  if (source === "deveco-code" && viaEnv) {
551
- const tokenDir = (0, import_path3.resolve)(viaEnv);
552
- return [{ source, tokenDir, keysDir: (0, import_path3.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
1054
+ const tokenDir = (0, import_path4.resolve)(viaEnv);
1055
+ return [{ source, tokenDir, keysDir: (0, import_path4.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
553
1056
  }
554
1057
  let dirs;
555
1058
  if (process.platform === "win32") {
556
- const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
557
- dirs = [(0, import_path3.join)(appData, appName), (0, import_path3.join)(home, ".config", appName)];
1059
+ const appData = process.env.APPDATA || (0, import_path4.join)(home, "AppData", "Roaming");
1060
+ dirs = [(0, import_path4.join)(appData, appName), (0, import_path4.join)(home, ".config", appName)];
558
1061
  } else if (process.platform === "darwin") {
559
1062
  dirs = [
560
- (0, import_path3.join)(configHome(), appName),
561
- (0, import_path3.join)(home, "Library", "Application Support", appName)
1063
+ (0, import_path4.join)(configHome(), appName),
1064
+ (0, import_path4.join)(home, "Library", "Application Support", appName)
562
1065
  ];
563
1066
  } else {
564
- dirs = [(0, import_path3.join)(configHome(), appName)];
1067
+ dirs = [(0, import_path4.join)(configHome(), appName)];
565
1068
  }
566
1069
  return dirs.map((tokenDir) => ({
567
1070
  source,
568
1071
  tokenDir,
569
- keysDir: (0, import_path3.join)(tokenDir, "keys"),
1072
+ keysDir: (0, import_path4.join)(tokenDir, "keys"),
570
1073
  via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
571
1074
  }));
572
1075
  }
573
1076
  function resolveLocation(source) {
574
1077
  const candidates = candidatesFor(source);
575
- const hit = candidates.find((c) => (0, import_fs4.existsSync)((0, import_path3.join)(c.tokenDir, "token.enc")));
1078
+ const hit = candidates.find((c) => (0, import_fs5.existsSync)((0, import_path4.join)(c.tokenDir, "token.enc")));
576
1079
  if (hit) {
577
1080
  return hit;
578
1081
  }
@@ -583,59 +1086,220 @@ ${tried}`
583
1086
  );
584
1087
  }
585
1088
  function loadDevecoLocalToken(source, authDir) {
586
- const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path3.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
1089
+ const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path4.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
587
1090
  const plaintext = decryptToken(location.tokenDir, location.keysDir);
588
1091
  const { jwt, expMs } = extractJwt(plaintext);
589
1092
  return { jwt, expMs, location };
590
1093
  }
591
1094
 
1095
+ // src/core/login-page.ts
1096
+ var SUCCESS_ICON = `<svg viewBox="0 0 88 88" width="88" height="88" aria-hidden="true"><circle cx="44" cy="44" r="40" fill="rgba(255,255,255,0.16)" stroke="#fff" stroke-width="2.5"/><path d="M27 46 L39 58 L62 33" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
1097
+ var FAILED_ICON = `<svg viewBox="0 0 88 88" width="88" height="88" aria-hidden="true"><circle cx="44" cy="44" r="40" fill="rgba(255,255,255,0.16)" stroke="#fff" stroke-width="2.5"/><path d="M33 33 L55 55 M55 33 L33 55" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round"/></svg>`;
1098
+ var PAGES = {
1099
+ success: {
1100
+ icon: SUCCESS_ICON,
1101
+ title: "\u767B\u5F55\u6210\u529F",
1102
+ message: "\u6388\u6743\u5DF2\u5B8C\u6210\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3\u5E76\u56DE\u5230\u7EC8\u7AEF",
1103
+ bgGradient: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
1104
+ },
1105
+ failed: {
1106
+ icon: FAILED_ICON,
1107
+ title: "\u767B\u5F55\u5931\u8D25",
1108
+ message: "\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5",
1109
+ bgGradient: "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)"
1110
+ }
1111
+ };
1112
+ var TEMPLATE = `<!DOCTYPE html>
1113
+ <html lang="zh-CN">
1114
+ <head>
1115
+ <meta charset="utf-8">
1116
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1117
+ <title>{{TITLE}}</title>
1118
+ <style>
1119
+ * { box-sizing: border-box; }
1120
+ body {
1121
+ margin: 0;
1122
+ min-height: 100vh;
1123
+ display: flex;
1124
+ align-items: center;
1125
+ justify-content: center;
1126
+ background: {{BG_GRADIENT}};
1127
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Roboto, sans-serif;
1128
+ -webkit-font-smoothing: antialiased;
1129
+ }
1130
+ .card {
1131
+ background: transparent;
1132
+ border-radius: 20px;
1133
+ padding: 48px 56px;
1134
+ text-align: center;
1135
+ max-width: 480px;
1136
+ }
1137
+ .icon {
1138
+ display: flex;
1139
+ justify-content: center;
1140
+ margin-bottom: 20px;
1141
+ animation: bounceIn 0.6s ease-out;
1142
+ }
1143
+ .icon svg { display: block; }
1144
+ h1 {
1145
+ margin: 0 0 12px;
1146
+ font-size: 26px;
1147
+ font-weight: 600;
1148
+ color: #fff;
1149
+ letter-spacing: 0.02em;
1150
+ }
1151
+ p {
1152
+ margin: 0;
1153
+ font-size: 15px;
1154
+ line-height: 1.6;
1155
+ color: rgba(255, 255, 255, 0.88);
1156
+ }
1157
+ @keyframes bounceIn {
1158
+ 0% { transform: scale(0); opacity: 0; }
1159
+ 50% { transform: scale(1.15); }
1160
+ 100% { transform: scale(1); opacity: 1; }
1161
+ }
1162
+ </style>
1163
+ </head>
1164
+ <body>
1165
+ <div class="card">
1166
+ <div class="icon">{{ICON}}</div>
1167
+ <h1>{{TITLE}}</h1>
1168
+ <p>{{MESSAGE}}</p>
1169
+ </div>
1170
+ </body>
1171
+ </html>`;
1172
+ function escapeHtml(value) {
1173
+ return value.replace(/[&<>"']/g, (ch) => {
1174
+ switch (ch) {
1175
+ case "&":
1176
+ return "&amp;";
1177
+ case "<":
1178
+ return "&lt;";
1179
+ case ">":
1180
+ return "&gt;";
1181
+ case '"':
1182
+ return "&quot;";
1183
+ case "'":
1184
+ return "&#39;";
1185
+ default:
1186
+ return ch;
1187
+ }
1188
+ });
1189
+ }
1190
+ function renderLoginPage(kind, options) {
1191
+ const vars = PAGES[kind];
1192
+ const message = options?.message?.trim() ? options.message : vars.message;
1193
+ return TEMPLATE.replace(/\{\{ICON\}\}/g, vars.icon).replace(/\{\{TITLE\}\}/g, escapeHtml(vars.title)).replace(/\{\{MESSAGE\}\}/g, escapeHtml(message)).replace(/\{\{BG_GRADIENT\}\}/g, vars.bgGradient);
1194
+ }
1195
+
592
1196
  // src/core/auth-mgr.ts
593
- var crypto2 = __toESM(require("crypto"));
1197
+ var crypto3 = __toESM(require("crypto"));
594
1198
  var http = __toESM(require("http"));
595
- var import_child_process = require("child_process");
596
- var import_fs5 = __toESM(require("fs"));
597
- var import_path4 = __toESM(require("path"));
598
- var import_os3 = __toESM(require("os"));
1199
+ var import_child_process2 = require("child_process");
1200
+ var import_fs6 = __toESM(require("fs"));
599
1201
  var DEVECO_CACHE_TTL_MS = 30 * 60 * 1e3;
1202
+ var OAUTH_EXPIRY_SKEW_MS = 5 * 60 * 1e3;
1203
+ function oauthAccessDecision(cache, now = Date.now(), skewMs = OAUTH_EXPIRY_SKEW_MS) {
1204
+ if (!cache?.accessToken) return "relogin";
1205
+ const expiresAt = cache.expiresAt;
1206
+ const hasExpiry = typeof expiresAt === "number" && Number.isFinite(expiresAt) && expiresAt > 0;
1207
+ if (!hasExpiry) return "use";
1208
+ if (expiresAt > now + skewMs) return "use";
1209
+ if (cache.refreshToken) return "refresh";
1210
+ return "relogin";
1211
+ }
1212
+ function resolveExpiresAt(expireTime, previousExpiresAt, now = Date.now()) {
1213
+ if (Number.isFinite(expireTime) && expireTime > 0) return now + expireTime * 1e3;
1214
+ if (typeof previousExpiresAt === "number" && Number.isFinite(previousExpiresAt) && previousExpiresAt > now + OAUTH_EXPIRY_SKEW_MS) {
1215
+ return previousExpiresAt;
1216
+ }
1217
+ return 0;
1218
+ }
1219
+ var NOT_LOGGED_IN = "Not logged in. Run `connect-api-cli auth login` and finish authorization in the browser.";
1220
+ var NEED_RELOGIN = "OAuth token refresh failed, need to re-login";
1221
+ var HARMONY_AA_CANDIDATES = ["/bin/aa", "/system/bin/aa", "/usr/bin/aa"];
1222
+ function detectBrowserHost(input) {
1223
+ const platform = input?.platform ?? process.platform;
1224
+ if (platform === "win32") return "win32";
1225
+ if (platform === "darwin") return "darwin";
1226
+ const osRelease = input?.osRelease ?? readOsRelease();
1227
+ const hasAa = input?.hasAa ?? harmonyAaExists();
1228
+ if (/harmonyos|openharmony/i.test(osRelease) || hasAa) return "harmony";
1229
+ return "linux";
1230
+ }
1231
+ function browserLaunchSpec(url, host = detectBrowserHost()) {
1232
+ if (host === "win32") {
1233
+ return { file: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
1234
+ }
1235
+ if (host === "darwin") {
1236
+ return { file: "open", args: [url] };
1237
+ }
1238
+ if (host === "harmony") {
1239
+ return { file: "aa", args: ["start", "-A", "ohos.want.action.viewData", "-U", url] };
1240
+ }
1241
+ return { file: "xdg-open", args: [url] };
1242
+ }
600
1243
  var AuthManager = class {
601
- static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
1244
+ /** 并发的 OAuth 登录共用同一次浏览器授权。 */
602
1245
  static pendingOAuthLogin;
1246
+ /** 并发请求共用一次刷新,避免同时打刷新接口或互相清缓存。 */
1247
+ static oauthRefreshInFlight = null;
603
1248
  /**
604
1249
  * 获取当前生效的 access token,并具备自动刷新能力:
605
- * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
1250
+ * - OAuth:未过期,或没有过期时间时,直接用缓存。过期且有 refreshToken 才刷新。
1251
+ * 请求路径不打开浏览器;需要重新授权时抛错,由 `auth login` 或 DevEco 降级处理。
606
1252
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
607
1253
  * - deveco:过期后重新解密本地登录态并 refresh 换取
608
1254
  *
609
- * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
1255
+ * force 跳过缓存(供 401 重试使用)。OAuth 在 force 时只走 refreshToken。
610
1256
  */
611
1257
  static async getAccessToken(force = false) {
612
1258
  const { config: config2, cache } = this.getStatus();
613
- return this.getToken(config2, cache, force);
614
- }
615
- static async getToken(cfg, cache, force = false) {
616
- if (!force && cache && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
1259
+ if (config2.authMode === "oauth") {
1260
+ return this.getOAuthAccessToken(config2, cache, force, false);
1261
+ }
1262
+ if (!force && cache && cache.expiresAt > Date.now() + OAUTH_EXPIRY_SKEW_MS) {
617
1263
  return cache.accessToken;
618
1264
  }
619
- if (cfg.authMode === "oauth" && cache?.refreshToken) {
1265
+ return this.acquire(config2);
1266
+ }
1267
+ /**
1268
+ * interactive 为真时,缓存不可用会打开浏览器。
1269
+ * 请求路径(interactive 为假)只使用或刷新已有 token,不会占用 12306。
1270
+ */
1271
+ static async getOAuthAccessToken(cfg, cache, force, interactive) {
1272
+ if (!force) {
1273
+ const decision = oauthAccessDecision(cache);
1274
+ if (decision === "use") return cache.accessToken;
1275
+ if (decision === "refresh") {
1276
+ try {
1277
+ return await this.refreshCachedOAuth(cfg, cache);
1278
+ } catch (e) {
1279
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache?.accessToken) {
1280
+ return cache.accessToken;
1281
+ }
1282
+ if (!interactive) throw e;
1283
+ }
1284
+ } else if (!interactive) {
1285
+ throw new Error(NOT_LOGGED_IN);
1286
+ }
1287
+ } else if (cache?.refreshToken) {
620
1288
  try {
621
- const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
622
- const expiresAt = Date.now() + refreshed.expireTime * 1e3;
623
- this.writeCache({
624
- accessToken: refreshed.accessToken,
625
- expiresAt,
626
- clientId: cfg.clientId,
627
- domain: cfg.domain,
628
- authMode: cfg.authMode,
629
- refreshToken: cache.refreshToken
630
- // 刷新接口不返回新 refreshToken,沿用旧值
631
- });
632
- return refreshed.accessToken;
1289
+ return await this.refreshCachedOAuth(cfg, cache);
633
1290
  } catch (e) {
634
- console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
635
- this.clearCache();
1291
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache.accessToken && !interactive) {
1292
+ return cache.accessToken;
1293
+ }
1294
+ if (!interactive) throw e;
636
1295
  }
1296
+ } else if (!interactive) {
1297
+ throw new Error(NOT_LOGGED_IN);
637
1298
  }
638
- return this.acquire(cfg);
1299
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
1300
+ this.pendingOAuthLogin = void 0;
1301
+ });
1302
+ return this.pendingOAuthLogin;
639
1303
  }
640
1304
  /** 登录入口:按当前认证模式获取并缓存 token */
641
1305
  static async login() {
@@ -645,10 +1309,8 @@ var AuthManager = class {
645
1309
  /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
646
1310
  static async acquire(cfg) {
647
1311
  if (cfg.authMode === "oauth") {
648
- this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
649
- this.pendingOAuthLogin = void 0;
650
- });
651
- return this.pendingOAuthLogin;
1312
+ const cache = this.matchingCache(cfg, this.readCache());
1313
+ return this.getOAuthAccessToken(cfg, cache, false, true);
652
1314
  }
653
1315
  if (cfg.authMode === "deveco") {
654
1316
  try {
@@ -658,7 +1320,7 @@ var AuthManager = class {
658
1320
  const oauthConfig = getConfig("oauth");
659
1321
  const cache = this.matchingCache(oauthConfig, this.readCache());
660
1322
  console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
661
- return this.getToken(oauthConfig, cache);
1323
+ return this.getOAuthAccessToken(oauthConfig, cache, false, true);
662
1324
  }
663
1325
  }
664
1326
  if (cfg.authMode === "service_account") {
@@ -689,51 +1351,68 @@ var AuthManager = class {
689
1351
  }
690
1352
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
691
1353
  }
692
- /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
1354
+ /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器。同一进程只开一次。 */
693
1355
  static loginOAuth(cfg) {
694
- return new Promise((resolve2, reject) => {
1356
+ return new Promise((resolve3, reject) => {
695
1357
  const redirectUri = cfg.oauth.redirectUri;
696
1358
  const port = Number(new URL(redirectUri).port || 80);
697
- const state = crypto2.randomBytes(32).toString("hex");
698
- const server = http.createServer(async (req, res) => {
1359
+ const state = crypto3.randomBytes(32).toString("hex");
1360
+ let settled = false;
1361
+ let server;
1362
+ const finish = (err, token) => {
1363
+ if (settled) return;
1364
+ settled = true;
1365
+ server.close();
1366
+ if (err) reject(err);
1367
+ else resolve3(token);
1368
+ };
1369
+ server = http.createServer(async (req, res) => {
699
1370
  try {
700
- const url = new URL(req.url, `http://${req.headers.host}`);
1371
+ const url = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
701
1372
  const code = url.searchParams.get("code");
702
1373
  const returnedState = url.searchParams.get("state");
703
- if (!code || returnedState !== state) {
704
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
705
- res.end("<h3>\u65E0\u6548\u7684\u56DE\u8C03\u53C2\u6570</h3>");
1374
+ const oauthError = url.searchParams.get("error");
1375
+ if (!code && !oauthError) {
1376
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
1377
+ res.end();
1378
+ return;
1379
+ }
1380
+ if (oauthError || !code || returnedState !== state) {
1381
+ const detail = oauthError ? `\u6388\u6743\u672A\u5B8C\u6210\uFF08${oauthError}\uFF09\u3002\u8BF7\u5173\u95ED\u9875\u9762\u540E\u91CD\u65B0\u6267\u884C auth login` : "\u56DE\u8C03\u53C2\u6570\u65E0\u6548\u3002\u8BF7\u5173\u95ED\u9875\u9762\u540E\u91CD\u65B0\u6267\u884C auth login";
1382
+ sendLoginPage(res, "failed", detail, 400);
1383
+ finish(new Error(detail));
706
1384
  return;
707
1385
  }
708
1386
  const token = await AuthService.getOAuthToken(code, redirectUri);
709
- const expiresAt = Date.now() + token.expireTime * 1e3;
710
1387
  clearOAuthTeamIdCache();
711
1388
  this.writeCache({
712
1389
  accessToken: token.accessToken,
713
- expiresAt,
1390
+ expiresAt: resolveExpiresAt(token.expireTime),
714
1391
  clientId: cfg.clientId,
715
1392
  domain: cfg.domain,
716
1393
  authMode: cfg.authMode,
717
1394
  refreshToken: token.refreshToken
718
1395
  });
719
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
720
- res.end('<!DOCTYPE html><html><body style="font-family:sans-serif;padding:40px;text-align:center"><h2>\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3</h2></body></html>');
721
- server.close();
722
- resolve2(token.accessToken);
1396
+ sendLoginPage(res, "success");
1397
+ finish(void 0, token.accessToken);
723
1398
  } catch (err) {
724
- server.close();
725
- reject(err instanceof Error ? err : new Error(String(err)));
1399
+ const message = err instanceof Error ? err.message : String(err);
1400
+ if (!res.headersSent) sendLoginPage(res, "failed", message || "\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5");
1401
+ finish(err instanceof Error ? err : new Error(message));
726
1402
  }
727
1403
  });
728
1404
  server.on("error", (err) => {
729
- server.close();
730
- reject(err);
1405
+ if (err.code === "EADDRINUSE") {
1406
+ finish(new Error("\u767B\u5F55\u9875\u5DF2\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\uFF0C\u8BF7\u5B8C\u6210\u6388\u6743\uFF0C\u4E0D\u8981\u91CD\u590D\u6253\u5F00\u3002"));
1407
+ return;
1408
+ }
1409
+ finish(err);
731
1410
  });
732
1411
  server.listen(port, () => {
733
1412
  const authUrl = AuthService.buildAuthUrl(state);
734
1413
  console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
735
1414
  console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
736
- openBrowser(authUrl);
1415
+ launchBrowser(authUrl);
737
1416
  });
738
1417
  });
739
1418
  }
@@ -770,53 +1449,458 @@ var AuthManager = class {
770
1449
  static matchingCache(cfg, cache) {
771
1450
  return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
772
1451
  }
773
- static readCache() {
1452
+ static refreshCachedOAuth(cfg, cache) {
1453
+ if (!this.oauthRefreshInFlight) {
1454
+ this.oauthRefreshInFlight = this.doRefreshCachedOAuth(cfg, cache).finally(() => {
1455
+ this.oauthRefreshInFlight = null;
1456
+ });
1457
+ }
1458
+ return this.oauthRefreshInFlight;
1459
+ }
1460
+ static async doRefreshCachedOAuth(cfg, cache) {
774
1461
  try {
775
- if (import_fs5.default.existsSync(this.cacheFile)) {
776
- const data = readPrivateFile(this.cacheFile);
777
- return JSON.parse(data);
778
- }
1462
+ const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
1463
+ const refreshToken = refreshed.refreshToken || cache.refreshToken;
1464
+ this.writeCache({
1465
+ accessToken: refreshed.accessToken,
1466
+ expiresAt: resolveExpiresAt(refreshed.expireTime, cache.expiresAt),
1467
+ clientId: cfg.clientId,
1468
+ domain: cfg.domain,
1469
+ authMode: cfg.authMode,
1470
+ refreshToken
1471
+ });
1472
+ return refreshed.accessToken;
779
1473
  } catch (e) {
1474
+ if (isDefinitiveOAuthRefreshFailure(e)) {
1475
+ console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
1476
+ this.clearCache();
1477
+ throw new Error(NEED_RELOGIN);
1478
+ }
1479
+ console.error("OAuth token refresh failed:", e instanceof Error ? e.message : String(e));
1480
+ throw e;
780
1481
  }
781
- return null;
1482
+ }
1483
+ static readCache() {
1484
+ const data = readVault(tokenFilePath());
1485
+ if (!data || typeof data !== "object") return null;
1486
+ const cache = data;
1487
+ return typeof cache.accessToken === "string" ? cache : null;
782
1488
  }
783
1489
  static writeCache(cache) {
784
- try {
785
- writePrivateFile(this.cacheFile, JSON.stringify(cache, null, 2));
786
- } catch (e) {
1490
+ const prev = this.readCache();
1491
+ const sameIdentity = !!prev && prev.clientId === cache.clientId && prev.domain === cache.domain && prev.authMode === cache.authMode;
1492
+ const next = { ...sameIdentity ? prev : {}, ...cache };
1493
+ if (cache.teamId === void 0 && sameIdentity && prev?.teamId) next.teamId = prev.teamId;
1494
+ if (Object.prototype.hasOwnProperty.call(cache, "refreshToken") && !cache.refreshToken) {
1495
+ delete next.refreshToken;
787
1496
  }
1497
+ writeVault(tokenFilePath(), next);
788
1498
  }
789
1499
  /**
790
1500
  * 清除缓存的 Token(登出)
791
1501
  */
792
1502
  static clearCache() {
793
1503
  clearOAuthTeamIdCache();
794
- try {
795
- if (import_fs5.default.existsSync(this.cacheFile)) {
796
- import_fs5.default.unlinkSync(this.cacheFile);
797
- return true;
798
- }
799
- return false;
800
- } catch (e) {
801
- return false;
802
- }
1504
+ return clearVault(tokenFilePath());
803
1505
  }
804
1506
  };
805
- function openBrowser(url) {
806
- const platform = process.platform;
807
- const cmd = platform === "darwin" ? "open" : platform === "win32" ? 'start ""' : "xdg-open";
808
- (0, import_child_process.exec)(`${cmd} "${url}"`, (err) => {
1507
+ function sendLoginPage(res, kind, message, status = 200) {
1508
+ const html = renderLoginPage(kind, message ? { message } : void 0);
1509
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
1510
+ res.end(html);
1511
+ }
1512
+ function launchBrowser(url) {
1513
+ const host = detectBrowserHost();
1514
+ const spec = browserLaunchSpec(url, host);
1515
+ if (host === "harmony") spec.file = resolveHarmonyAa();
1516
+ (0, import_child_process2.execFile)(spec.file, spec.args, { windowsHide: true }, (err) => {
809
1517
  if (err) {
810
1518
  console.error("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u9762\u7684\u94FE\u63A5\u8BBF\u95EE\u3002");
811
1519
  }
812
1520
  });
813
1521
  }
1522
+ function readOsRelease() {
1523
+ try {
1524
+ if (import_fs6.default.existsSync("/etc/os-release")) return import_fs6.default.readFileSync("/etc/os-release", "utf8");
1525
+ } catch {
1526
+ }
1527
+ return "";
1528
+ }
1529
+ function harmonyAaExists() {
1530
+ return HARMONY_AA_CANDIDATES.some((file) => import_fs6.default.existsSync(file));
1531
+ }
1532
+ function resolveHarmonyAa() {
1533
+ return HARMONY_AA_CANDIDATES.find((file) => import_fs6.default.existsSync(file)) ?? "aa";
1534
+ }
1535
+
1536
+ // src/core/age-rating-capture.ts
1537
+ var import_child_process3 = require("child_process");
1538
+ var fs6 = __toESM(require("fs"));
1539
+ var http2 = __toESM(require("http"));
1540
+ var path4 = __toESM(require("path"));
1541
+ var AGE_RATING_QUESTIONNAIRE_IDS = {
1542
+ cn: { app: "171592594061778711", game: "171592594061777702" },
1543
+ en: { app: "171592594061815538", game: "171592594061811078" },
1544
+ ru: { app: "171592594061816264", game: "171592594061813750" }
1545
+ };
1546
+ var FEEDBACK_MAX = 8192;
1547
+ var BODY_LIMIT = 2e4;
1548
+ function isolatedBrowserArgs(url) {
1549
+ return ["--guest", "--no-first-run", "--no-default-browser-check", "--new-window", url];
1550
+ }
1551
+ function findIsolatedBrowser(input) {
1552
+ const platform = input?.platform ?? process.platform;
1553
+ const env = input?.env ?? process.env;
1554
+ const exists = input?.exists ?? fs6.existsSync;
1555
+ return browserCandidates(platform, env).find((file) => exists(file));
1556
+ }
1557
+ function browserCandidates(platform, env) {
1558
+ if (platform === "win32") {
1559
+ const local = env.LOCALAPPDATA;
1560
+ const pf = env.ProgramFiles;
1561
+ const pf86 = env["ProgramFiles(x86)"];
1562
+ return [
1563
+ local && path4.join(local, "Google", "Chrome", "Application", "chrome.exe"),
1564
+ pf && path4.join(pf, "Google", "Chrome", "Application", "chrome.exe"),
1565
+ pf86 && path4.join(pf86, "Google", "Chrome", "Application", "chrome.exe"),
1566
+ local && path4.join(local, "Microsoft", "Edge", "Application", "msedge.exe"),
1567
+ pf && path4.join(pf, "Microsoft", "Edge", "Application", "msedge.exe"),
1568
+ pf86 && path4.join(pf86, "Microsoft", "Edge", "Application", "msedge.exe")
1569
+ ].filter((file) => Boolean(file));
1570
+ }
1571
+ if (platform === "darwin") {
1572
+ const home = env.HOME || "";
1573
+ return [
1574
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
1575
+ home && path4.join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
1576
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
1577
+ ].filter((file) => Boolean(file));
1578
+ }
1579
+ return [
1580
+ "/usr/bin/google-chrome",
1581
+ "/usr/bin/google-chrome-stable",
1582
+ "/usr/bin/chromium",
1583
+ "/usr/bin/chromium-browser",
1584
+ "/usr/bin/microsoft-edge",
1585
+ "/usr/bin/microsoft-edge-stable"
1586
+ ];
1587
+ }
1588
+ function launchIsolatedBrowser(url) {
1589
+ const file = findIsolatedBrowser();
1590
+ if (!file) return false;
1591
+ (0, import_child_process3.execFile)(file, isolatedBrowserArgs(url), (err) => {
1592
+ if (err) {
1593
+ console.error("\u65E0\u6CD5\u6253\u5F00\u672A\u767B\u5F55\u7684\u6D4F\u89C8\u5668\u7A97\u53E3\u3002\u8BF7\u624B\u52A8\u7528\u672A\u767B\u5F55\u7684 Chrome \u6253\u5F00\u4E0A\u9762\u7684\u5730\u5740\u3002");
1594
+ }
1595
+ });
1596
+ return true;
1597
+ }
1598
+ function ageRatingQuestionnaireUrl(appType, lang) {
1599
+ const params = new URLSearchParams({ appType, lang });
1600
+ return `https://developer.huawei.com/consumer/cn/service/josp/agc/amp/ageRatingQuestionnaire.html#/?${params.toString()}`;
1601
+ }
1602
+ function buildAgeRatingBody(feedback, expectedQuestionnaireId) {
1603
+ if (typeof feedback !== "string" || !feedback.trim()) {
1604
+ throw new Error("\u95EE\u5377\u6CA1\u6709\u8FD4\u56DE feedback");
1605
+ }
1606
+ if (Buffer.byteLength(feedback) > FEEDBACK_MAX) {
1607
+ throw new Error(`feedback \u8D85\u8FC7 ${FEEDBACK_MAX} \u5B57\u8282`);
1608
+ }
1609
+ let parsed;
1610
+ try {
1611
+ parsed = JSON.parse(feedback);
1612
+ } catch {
1613
+ throw new Error("feedback \u4E0D\u662F JSON");
1614
+ }
1615
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1616
+ throw new Error("feedback \u4E0D\u662F\u95EE\u5377\u5BF9\u8C61");
1617
+ }
1618
+ const record = parsed;
1619
+ const questionnaireId = typeof record.questionnaireId === "string" ? record.questionnaireId : "";
1620
+ if (!questionnaireId) {
1621
+ throw new Error("questionnaireId is empty");
1622
+ }
1623
+ if (questionnaireId !== expectedQuestionnaireId) {
1624
+ throw new Error(`questionnaireId \u4E0E\u6240\u9009\u95EE\u5377\u4E0D\u4E00\u81F4\uFF0C\u671F\u671B ${expectedQuestionnaireId}`);
1625
+ }
1626
+ if (!Array.isArray(record.details) || record.details.length === 0) {
1627
+ throw new Error("\u95EE\u5377\u6CA1\u6709\u4F5C\u7B54\u660E\u7EC6");
1628
+ }
1629
+ return { feedback, ratingRule: 0 };
1630
+ }
1631
+ function renderAgeRatingCapturePage(questionnaireUrl) {
1632
+ const urlJson = JSON.stringify(questionnaireUrl);
1633
+ return `<!DOCTYPE html>
1634
+ <html lang="zh-CN">
1635
+ <head>
1636
+ <meta charset="utf-8">
1637
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1638
+ <title>\u5E74\u9F84\u5206\u7EA7\u95EE\u5377</title>
1639
+ <style>
1640
+ * { box-sizing: border-box; }
1641
+ body {
1642
+ margin: 0;
1643
+ min-height: 100vh;
1644
+ display: flex;
1645
+ align-items: center;
1646
+ justify-content: center;
1647
+ padding: 28px 16px;
1648
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1649
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Roboto, sans-serif;
1650
+ -webkit-font-smoothing: antialiased;
1651
+ color: #1f2328;
1652
+ }
1653
+ main {
1654
+ width: min(440px, 100%);
1655
+ background: #fff;
1656
+ border-radius: 20px;
1657
+ padding: 36px 32px 28px;
1658
+ box-shadow: 0 18px 50px rgba(49, 28, 89, 0.28);
1659
+ animation: rise 0.45s ease-out;
1660
+ }
1661
+ .mark {
1662
+ width: 64px;
1663
+ height: 64px;
1664
+ margin: 0 auto 16px;
1665
+ display: grid;
1666
+ place-items: center;
1667
+ border-radius: 18px;
1668
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1669
+ box-shadow: 0 8px 18px rgba(102, 126, 234, 0.35);
1670
+ }
1671
+ .mark svg { display: block; }
1672
+ h1 {
1673
+ margin: 0 0 8px;
1674
+ text-align: center;
1675
+ font-size: 24px;
1676
+ font-weight: 600;
1677
+ letter-spacing: 0.02em;
1678
+ }
1679
+ .lead {
1680
+ margin: 0 0 22px;
1681
+ text-align: center;
1682
+ text-wrap: balance;
1683
+ font-size: 14px;
1684
+ line-height: 1.65;
1685
+ color: #5c6570;
1686
+ }
1687
+ ol {
1688
+ list-style: none;
1689
+ margin: 0 0 22px;
1690
+ padding: 0;
1691
+ display: grid;
1692
+ gap: 10px;
1693
+ }
1694
+ li {
1695
+ display: flex;
1696
+ align-items: center;
1697
+ gap: 12px;
1698
+ min-height: 44px;
1699
+ padding: 8px 12px;
1700
+ border-radius: 12px;
1701
+ background: #f6f7fb;
1702
+ font-size: 14px;
1703
+ }
1704
+ .n {
1705
+ width: 22px;
1706
+ height: 22px;
1707
+ flex: none;
1708
+ border-radius: 50%;
1709
+ display: grid;
1710
+ place-items: center;
1711
+ background: #ece9fb;
1712
+ color: #5b4b8a;
1713
+ font-size: 12px;
1714
+ font-weight: 650;
1715
+ }
1716
+ button {
1717
+ appearance: none;
1718
+ width: 100%;
1719
+ border: 0;
1720
+ border-radius: 12px;
1721
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1722
+ color: #fff;
1723
+ font: inherit;
1724
+ font-size: 15px;
1725
+ font-weight: 600;
1726
+ letter-spacing: 0.04em;
1727
+ padding: 12px 16px;
1728
+ cursor: pointer;
1729
+ box-shadow: 0 8px 18px rgba(102, 126, 234, 0.32);
1730
+ }
1731
+ button:hover { filter: brightness(1.06); }
1732
+ button:focus-visible { outline: 3px solid rgba(102, 126, 234, 0.45); outline-offset: 3px; }
1733
+ #out {
1734
+ margin: 16px 0 0;
1735
+ min-height: 22px;
1736
+ text-align: center;
1737
+ font-size: 13px;
1738
+ line-height: 1.5;
1739
+ color: #6b7280;
1740
+ }
1741
+ #out.wait { color: #5b4b8a; }
1742
+ #out.ok { color: #0f7b4c; font-weight: 600; }
1743
+ #out.err { color: #c24141; }
1744
+ @keyframes rise {
1745
+ from { transform: translateY(10px); opacity: 0; }
1746
+ to { transform: none; opacity: 1; }
1747
+ }
1748
+ </style>
1749
+ </head>
1750
+ <body>
1751
+ <main>
1752
+ <div class="mark" aria-hidden="true">
1753
+ <svg viewBox="0 0 32 32" width="30" height="30">
1754
+ <path d="M8 7.5h16a2 2 0 0 1 2 2v15l-4.2-2.4a1 1 0 0 0-.5-.1H8a2 2 0 0 1-2-2v-10.5a2 2 0 0 1 2-2z" fill="none" stroke="#fff" stroke-width="1.8" stroke-linejoin="round"/>
1755
+ <path d="M11 13.5h10M11 17.5h6" fill="none" stroke="#fff" stroke-width="1.8" stroke-linecap="round"/>
1756
+ </svg>
1757
+ </div>
1758
+ <h1>\u5E74\u9F84\u5206\u7EA7\u95EE\u5377</h1>
1759
+ <p class="lead">\u6309\u5E94\u7528\u771F\u5B9E\u5185\u5BB9\u4F5C\u7B54<br>\u8BF7\u5728\u8FD9\u4E2A\u672A\u767B\u5F55\u7A97\u53E3\u91CC\u6253\u5F00\u95EE\u5377</p>
1760
+ <ol>
1761
+ <li><span class="n">1</span>\u6253\u5F00\u5B98\u65B9\u95EE\u5377</li>
1762
+ <li><span class="n">2</span>\u6309\u771F\u5B9E\u5185\u5BB9\u9010\u9898\u4F5C\u7B54</li>
1763
+ <li><span class="n">3</span>\u63D0\u4EA4\u540E\u56DE\u5230\u7EC8\u7AEF\u7EE7\u7EED</li>
1764
+ </ol>
1765
+ <button id="open" type="button">\u6253\u5F00\u95EE\u5377</button>
1766
+ <p id="out">\u5C1A\u672A\u6253\u5F00\u95EE\u5377\u3002</p>
1767
+ </main>
1768
+ <script>
1769
+ const questionnaireUrl = ${urlJson};
1770
+ const out = document.getElementById('out');
1771
+ const setStatus = (text, state) => {
1772
+ out.textContent = text;
1773
+ out.className = state || '';
1774
+ };
1775
+ document.getElementById('open').onclick = () => {
1776
+ window.open(questionnaireUrl, 'ageRating');
1777
+ setStatus('\u8BF7\u5728\u65B0\u7A97\u53E3\u5B8C\u6210\u95EE\u5377\u5E76\u63D0\u4EA4\u3002', 'wait');
1778
+ };
1779
+ window.addEventListener('message', async (event) => {
1780
+ let host = '';
1781
+ try { host = new URL(event.origin).hostname; } catch (e) { return; }
1782
+ if (host !== 'developer.huawei.com' && host !== 'developer.huawei.ru') return;
1783
+ const feedback = typeof event.data === 'string' ? event.data : JSON.stringify(event.data);
1784
+ setStatus('\u6B63\u5728\u4FDD\u5B58\u2026', 'wait');
1785
+ const res = await fetch('/feedback', {
1786
+ method: 'POST',
1787
+ headers: { 'Content-Type': 'application/json' },
1788
+ body: JSON.stringify({ feedback })
1789
+ });
1790
+ const data = await res.json().catch(() => ({}));
1791
+ setStatus(res.ok ? '\u5DF2\u4FDD\u5B58\uFF0C\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u5E76\u56DE\u5230\u7EC8\u7AEF\u3002' : (data.message || '\u4FDD\u5B58\u5931\u8D25'), res.ok ? 'ok' : 'err');
1792
+ });
1793
+ </script>
1794
+ </body>
1795
+ </html>`;
1796
+ }
1797
+ function readBody(req, limit) {
1798
+ return new Promise((resolve3, reject) => {
1799
+ const chunks = [];
1800
+ let size = 0;
1801
+ req.on("data", (chunk) => {
1802
+ size += chunk.length;
1803
+ if (size > limit) {
1804
+ reject(new Error("\u8BF7\u6C42\u4F53\u8FC7\u5927"));
1805
+ req.destroy();
1806
+ return;
1807
+ }
1808
+ chunks.push(chunk);
1809
+ });
1810
+ req.on("end", () => resolve3(Buffer.concat(chunks).toString("utf8")));
1811
+ req.on("error", reject);
1812
+ });
1813
+ }
1814
+ function captureAgeRatingFeedback(options) {
1815
+ const questionnaireId = AGE_RATING_QUESTIONNAIRE_IDS[options.lang][options.appType];
1816
+ const html = renderAgeRatingCapturePage(ageRatingQuestionnaireUrl(options.appType, options.lang));
1817
+ const outFile = path4.resolve(options.outFile);
1818
+ return new Promise((resolve3, reject) => {
1819
+ let settled = false;
1820
+ const server = http2.createServer((req, res) => {
1821
+ const url = new URL(req.url || "/", "http://127.0.0.1");
1822
+ if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) {
1823
+ res.writeHead(200, {
1824
+ "Content-Type": "text/html; charset=utf-8",
1825
+ "Cache-Control": "no-store"
1826
+ });
1827
+ res.end(html);
1828
+ return;
1829
+ }
1830
+ if (req.method !== "POST" || url.pathname !== "/feedback") {
1831
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
1832
+ res.end();
1833
+ return;
1834
+ }
1835
+ readBody(req, BODY_LIMIT).then((raw) => {
1836
+ try {
1837
+ const payload = JSON.parse(raw);
1838
+ if (typeof payload.feedback !== "string") throw new Error("feedback \u7F3A\u5931");
1839
+ const body = buildAgeRatingBody(payload.feedback, questionnaireId);
1840
+ const text = `${JSON.stringify(body, null, 2)}
1841
+ `;
1842
+ fs6.mkdirSync(path4.dirname(outFile), { recursive: true });
1843
+ fs6.writeFileSync(outFile, text, "utf8");
1844
+ const parsed = JSON.parse(body.feedback);
1845
+ const result = {
1846
+ outFile,
1847
+ questionnaireId,
1848
+ detailCount: parsed.details.length,
1849
+ bytes: Buffer.byteLength(body.feedback)
1850
+ };
1851
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
1852
+ res.end(JSON.stringify({ ok: true }), () => finish(void 0, result));
1853
+ } catch (error) {
1854
+ const message = error instanceof Error ? error.message : String(error);
1855
+ if (!res.headersSent) {
1856
+ res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
1857
+ res.end(JSON.stringify({ message }));
1858
+ }
1859
+ }
1860
+ }).catch((error) => {
1861
+ const message = error instanceof Error ? error.message : String(error);
1862
+ if (!res.headersSent) {
1863
+ res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
1864
+ res.end(JSON.stringify({ message }));
1865
+ }
1866
+ });
1867
+ });
1868
+ const timer = setTimeout(() => {
1869
+ finish(new Error("\u7B49\u5F85\u95EE\u5377\u63D0\u4EA4\u8D85\u65F6\u3002\u8BF7\u91CD\u65B0\u8FD0\u884C publish age-rating-capture\u3002"));
1870
+ }, options.timeoutMs);
1871
+ timer.unref?.();
1872
+ function finish(error, result) {
1873
+ if (settled) return;
1874
+ settled = true;
1875
+ clearTimeout(timer);
1876
+ server.close();
1877
+ if (error) reject(error);
1878
+ else resolve3(result);
1879
+ }
1880
+ server.on("error", (error) => finish(error));
1881
+ server.listen(0, "127.0.0.1", () => {
1882
+ const address = server.address();
1883
+ if (!address || typeof address === "string") {
1884
+ finish(new Error("\u672C\u5730\u95EE\u5377\u9875\u542F\u52A8\u5931\u8D25"));
1885
+ return;
1886
+ }
1887
+ const localUrl = `http://127.0.0.1:${address.port}/`;
1888
+ console.error("\u8BF7\u5728\u81EA\u52A8\u6253\u5F00\u7684\u672A\u767B\u5F55\u7A97\u53E3\u91CC\u70B9\u51FB\u300C\u6253\u5F00\u95EE\u5377\u300D\uFF0C\u6309\u5E94\u7528\u771F\u5B9E\u5185\u5BB9\u4F5C\u7B54\u5E76\u63D0\u4EA4\u3002");
1889
+ console.error("\u4E0D\u8981\u628A\u8FD9\u4E2A\u5730\u5740\u8D34\u8FDB\u5DF2\u7ECF\u767B\u5F55\u534E\u4E3A\u5F00\u53D1\u8005\u8D26\u53F7\u7684 Chrome\u3002\u90A3\u79CD\u7A97\u53E3\u6253\u5F00\u95EE\u5377\u4F1A\u63D0\u793A\u300C\u5904\u7406\u8BF7\u6C42\u65F6\u53D1\u751F\u672A\u77E5\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u300D\u3002");
1890
+ console.error(`\u82E5\u7A97\u53E3\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u7528\u672A\u767B\u5F55\u7684\u6D4F\u89C8\u5668\u8BBF\u95EE: ${localUrl}`);
1891
+ options.onReady?.(localUrl);
1892
+ if (options.open !== false && !launchIsolatedBrowser(localUrl)) {
1893
+ console.error("\u672A\u627E\u5230 Chrome \u6216 Edge\uFF0C\u8BF7\u81EA\u884C\u7528\u672A\u767B\u5F55\u7684\u6D4F\u89C8\u5668\u6253\u5F00\u4E0A\u9762\u7684\u5730\u5740\u3002");
1894
+ }
1895
+ });
1896
+ });
1897
+ }
814
1898
 
815
1899
  // src/core/http.ts
816
1900
  var import_axios3 = __toESM(require("axios"));
817
1901
 
818
1902
  // src/core/request-source.ts
819
- var import_fs6 = __toESM(require("fs"));
1903
+ var import_fs7 = __toESM(require("fs"));
820
1904
  var import_path5 = __toESM(require("path"));
821
1905
  var REQUEST_SOURCE_HEADER = "Request-Source";
822
1906
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
@@ -957,7 +2041,7 @@ function getRequestSource() {
957
2041
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
958
2042
  }
959
2043
  function readVersion() {
960
- const fromBuild = injected(true ? "1.1.9" : void 0);
2044
+ const fromBuild = injected(true ? "1.1.11" : void 0);
961
2045
  if (fromBuild) return fromBuild;
962
2046
  const candidates = [
963
2047
  import_path5.default.join(__dirname, "..", "..", "package.json"),
@@ -965,7 +2049,7 @@ function readVersion() {
965
2049
  ];
966
2050
  for (const pkgPath of candidates) {
967
2051
  try {
968
- const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
2052
+ const pkg = JSON.parse(import_fs7.default.readFileSync(pkgPath, "utf8"));
969
2053
  if (pkg.version) return pkg.version;
970
2054
  } catch {
971
2055
  }
@@ -1059,7 +2143,7 @@ connectApiClient.interceptors.response.use(
1059
2143
  original._retry = true;
1060
2144
  try {
1061
2145
  const cfg = getConfig();
1062
- const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
2146
+ const newToken = await AuthManager.getAccessToken(true);
1063
2147
  if (!original.headers) {
1064
2148
  original.headers = {};
1065
2149
  }
@@ -1067,6 +2151,10 @@ connectApiClient.interceptors.response.use(
1067
2151
  if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1068
2152
  return connectApiClient(original);
1069
2153
  } catch (e) {
2154
+ if (e instanceof Error && e.message) {
2155
+ err.message = `${err.message}
2156
+ ${e.message}`;
2157
+ }
1070
2158
  return Promise.reject(err);
1071
2159
  }
1072
2160
  }
@@ -1539,7 +2627,7 @@ var ProvisionService = class {
1539
2627
 
1540
2628
  // src/services/upload.ts
1541
2629
  var import_axios4 = __toESM(require("axios"));
1542
- var import_fs7 = __toESM(require("fs"));
2630
+ var import_fs8 = __toESM(require("fs"));
1543
2631
  var import_path6 = __toESM(require("path"));
1544
2632
  function pickObjectId(res) {
1545
2633
  return res.urlInfo?.objectId || res.objectId;
@@ -1579,7 +2667,7 @@ var UploadService = class {
1579
2667
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1580
2668
  */
1581
2669
  static async uploadFile(options) {
1582
- const stat = import_fs7.default.statSync(options.filePath);
2670
+ const stat = import_fs8.default.statSync(options.filePath);
1583
2671
  const fileName = import_path6.default.basename(options.filePath) || "unknown";
1584
2672
  if (stat.size < 5 * 1024 * 1024) {
1585
2673
  return this.uploadSingleFile(options, fileName, stat.size);
@@ -1621,7 +2709,7 @@ var UploadService = class {
1621
2709
  );
1622
2710
  }
1623
2711
  const { url, headers } = urlRes.urlInfo;
1624
- const fileStream = import_fs7.default.createReadStream(options.filePath);
2712
+ const fileStream = import_fs8.default.createReadStream(options.filePath);
1625
2713
  await import_axios4.default.put(url, fileStream, {
1626
2714
  headers: this.buildObsPutHeaders(headers, contentLength),
1627
2715
  maxBodyLength: Infinity,
@@ -1662,7 +2750,7 @@ var UploadService = class {
1662
2750
  if (!uploadInfoMap) {
1663
2751
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1664
2752
  }
1665
- const fd = import_fs7.default.openSync(options.filePath, "r");
2753
+ const fd = import_fs8.default.openSync(options.filePath, "r");
1666
2754
  const composeReqBody = {};
1667
2755
  for (let i = 1; i <= partsCount; i++) {
1668
2756
  const propKey = `additionalProp${i}`;
@@ -1671,7 +2759,7 @@ var UploadService = class {
1671
2759
  const end = Math.min(start + partSize, fileSize);
1672
2760
  const length = end - start;
1673
2761
  const buffer = Buffer.alloc(length);
1674
- import_fs7.default.readSync(fd, buffer, 0, length, start);
2762
+ import_fs8.default.readSync(fd, buffer, 0, length, start);
1675
2763
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1676
2764
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1677
2765
  maxBodyLength: Infinity,
@@ -1683,7 +2771,7 @@ var UploadService = class {
1683
2771
  etag
1684
2772
  };
1685
2773
  }
1686
- import_fs7.default.closeSync(fd);
2774
+ import_fs8.default.closeSync(fd);
1687
2775
  await this.composeMultipart({
1688
2776
  objectId,
1689
2777
  nspUploadId,
@@ -1694,7 +2782,7 @@ var UploadService = class {
1694
2782
  };
1695
2783
 
1696
2784
  // src/services/domain.ts
1697
- var import_fs8 = __toESM(require("fs"));
2785
+ var import_fs9 = __toESM(require("fs"));
1698
2786
  var DomainService = class {
1699
2787
  /**
1700
2788
  * 查询元服务的域名配置信息
@@ -1746,8 +2834,8 @@ var DomainService = class {
1746
2834
  responseType: "stream"
1747
2835
  }
1748
2836
  );
1749
- return new Promise((resolve2, reject) => {
1750
- const writer = import_fs8.default.createWriteStream(outputPath);
2837
+ return new Promise((resolve3, reject) => {
2838
+ const writer = import_fs9.default.createWriteStream(outputPath);
1751
2839
  response.data.pipe(writer);
1752
2840
  let error = null;
1753
2841
  writer.on("error", (err) => {
@@ -1757,7 +2845,7 @@ var DomainService = class {
1757
2845
  });
1758
2846
  writer.on("close", () => {
1759
2847
  if (!error) {
1760
- resolve2();
2848
+ resolve3();
1761
2849
  }
1762
2850
  });
1763
2851
  });
@@ -1778,10 +2866,10 @@ var DomainService = class {
1778
2866
  };
1779
2867
 
1780
2868
  // src/services/sign.ts
1781
- var import_fs9 = __toESM(require("fs"));
2869
+ var import_fs10 = __toESM(require("fs"));
1782
2870
  var import_os4 = __toESM(require("os"));
1783
2871
  var import_path7 = __toESM(require("path"));
1784
- var import_child_process2 = require("child_process");
2872
+ var import_child_process4 = require("child_process");
1785
2873
  var import_crypto2 = __toESM(require("crypto"));
1786
2874
  var DEFAULT_SIGN_OUT_DIR = ".certs";
1787
2875
  var SIGN_FILE_PREFIX = {
@@ -1837,8 +2925,8 @@ var SignService = class {
1837
2925
  */
1838
2926
  static resolveSignTool(sdkPath) {
1839
2927
  const { jar, native } = this.signToolCandidates(sdkPath);
1840
- if (import_fs9.default.existsSync(jar)) return { mode: "jar", path: jar };
1841
- if (import_fs9.default.existsSync(native)) return { mode: "native", path: native };
2928
+ if (import_fs10.default.existsSync(jar)) return { mode: "jar", path: jar };
2929
+ if (import_fs10.default.existsSync(native)) return { mode: "native", path: native };
1842
2930
  return void 0;
1843
2931
  }
1844
2932
  static async createSignP12AndCsr(options) {
@@ -1864,18 +2952,18 @@ var SignService = class {
1864
2952
  throw new Error(`hap-sign-tool not found at ${jar} or ${native}`);
1865
2953
  }
1866
2954
  const { rootDir, bundleDir, filename } = this.resolveSignOutputLayout(options);
1867
- const createdBundleDir = !import_fs9.default.existsSync(bundleDir);
1868
- if (!import_fs9.default.existsSync(rootDir)) {
1869
- import_fs9.default.mkdirSync(rootDir, { recursive: true });
2955
+ const createdBundleDir = !import_fs10.default.existsSync(bundleDir);
2956
+ if (!import_fs10.default.existsSync(rootDir)) {
2957
+ import_fs10.default.mkdirSync(rootDir, { recursive: true });
1870
2958
  }
1871
- import_fs9.default.mkdirSync(bundleDir, { recursive: true });
2959
+ import_fs10.default.mkdirSync(bundleDir, { recursive: true });
1872
2960
  const p12FilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "p12"));
1873
2961
  const csrFilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "csr"));
1874
2962
  const alias = options.alias;
1875
2963
  try {
1876
2964
  this.doCreateSignFileP12(javaPath, signTool, alias, pwd, p12FilePath);
1877
2965
  this.doCreateSignFileCsr(javaPath, signTool, alias, pwd, p12FilePath, csrFilePath);
1878
- const csrContent = import_fs9.default.readFileSync(csrFilePath, "utf8");
2966
+ const csrContent = import_fs10.default.readFileSync(csrFilePath, "utf8");
1879
2967
  const materialPath = this.placeMaterialBesideStore(bundleDir);
1880
2968
  return {
1881
2969
  alias,
@@ -1891,7 +2979,7 @@ var SignService = class {
1891
2979
  };
1892
2980
  } catch (err) {
1893
2981
  if (createdBundleDir) {
1894
- import_fs9.default.rmSync(bundleDir, { recursive: true, force: true });
2982
+ import_fs10.default.rmSync(bundleDir, { recursive: true, force: true });
1895
2983
  }
1896
2984
  throw err;
1897
2985
  }
@@ -1914,14 +3002,14 @@ var SignService = class {
1914
3002
  */
1915
3003
  static placeMaterialBesideStore(bundleDir, configDir) {
1916
3004
  const dest = import_path7.default.join(bundleDir, "material");
1917
- if (import_fs9.default.existsSync(dest)) {
3005
+ if (import_fs10.default.existsSync(dest)) {
1918
3006
  return dest;
1919
3007
  }
1920
3008
  const src = this.ensureMaterial(this.resolveOhosConfigDir(configDir));
1921
3009
  try {
1922
- import_fs9.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
3010
+ import_fs10.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1923
3011
  } catch {
1924
- import_fs9.default.cpSync(src, dest, { recursive: true });
3012
+ import_fs10.default.cpSync(src, dest, { recursive: true });
1925
3013
  }
1926
3014
  return dest;
1927
3015
  }
@@ -1939,12 +3027,12 @@ var SignService = class {
1939
3027
  static runSignTool(javaPath, tool, toolArgs) {
1940
3028
  if (tool.mode === "native") {
1941
3029
  console.error(`Executing: ${tool.path} ${this.maskArgs(toolArgs)}`);
1942
- (0, import_child_process2.execFileSync)(tool.path, toolArgs, { stdio: ["ignore", 2, "inherit"] });
3030
+ (0, import_child_process4.execFileSync)(tool.path, toolArgs, { stdio: ["ignore", 2, "inherit"] });
1943
3031
  return;
1944
3032
  }
1945
3033
  const args = ["-jar", tool.path, ...toolArgs];
1946
3034
  console.error(`Executing: ${javaPath} ${this.maskArgs(args)}`);
1947
- (0, import_child_process2.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
3035
+ (0, import_child_process4.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
1948
3036
  }
1949
3037
  static doCreateSignFileP12(javaPath, tool, alias, pwd, outFilePath) {
1950
3038
  const args = [
@@ -1986,12 +3074,12 @@ var SignService = class {
1986
3074
  }
1987
3075
  static COMPONENT = new Int8Array([49, 243, 9, 115, 214, 175, 91, 184, 211, 190, 177, 88, 101, 131, 192, 119]);
1988
3076
  static readDirBytes(dirPath) {
1989
- const entries = import_fs9.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1990
- return new Int8Array(import_fs9.default.readFileSync(import_path7.default.resolve(dirPath, entries[0])));
3077
+ const entries = import_fs10.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
3078
+ return new Int8Array(import_fs10.default.readFileSync(import_path7.default.resolve(dirPath, entries[0])));
1991
3079
  }
1992
3080
  static readFd(materialPath) {
1993
3081
  const fdDir = import_path7.default.resolve(materialPath, "fd");
1994
- return import_fs9.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
3082
+ return import_fs10.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
1995
3083
  }
1996
3084
  static xorBuffers(a, b) {
1997
3085
  const result = new Int8Array(a.byteLength);
@@ -2059,22 +3147,22 @@ var SignService = class {
2059
3147
  */
2060
3148
  static ensureMaterial(configDir) {
2061
3149
  const materialDir = import_path7.default.resolve(configDir, "material");
2062
- if (!import_fs9.default.existsSync(materialDir)) this.generateMaterial(configDir);
3150
+ if (!import_fs10.default.existsSync(materialDir)) this.generateMaterial(configDir);
2063
3151
  return materialDir;
2064
3152
  }
2065
3153
  static generateMaterial(configDir) {
2066
3154
  const materialDir = import_path7.default.resolve(configDir, "material");
2067
- if (import_fs9.default.existsSync(materialDir)) return;
2068
- import_fs9.default.mkdirSync(configDir, { recursive: true, mode: 448 });
3155
+ if (import_fs10.default.existsSync(materialDir)) return;
3156
+ import_fs10.default.mkdirSync(configDir, { recursive: true, mode: 448 });
2069
3157
  const staging = import_path7.default.join(configDir, `.material-${import_crypto2.default.randomBytes(8).toString("hex")}`);
2070
3158
  const acDir = import_path7.default.join(staging, "ac");
2071
3159
  const ceDir = import_path7.default.join(staging, "ce");
2072
- import_fs9.default.mkdirSync(acDir, { recursive: true, mode: 448 });
2073
- import_fs9.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
3160
+ import_fs10.default.mkdirSync(acDir, { recursive: true, mode: 448 });
3161
+ import_fs10.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
2074
3162
  const salt = import_crypto2.default.randomBytes(16);
2075
3163
  const components = [0, 1, 2].map(() => new Int8Array(import_crypto2.default.randomBytes(16)));
2076
3164
  for (let i = 0; i < components.length; i++) {
2077
- import_fs9.default.mkdirSync(import_path7.default.join(staging, "fd", String(i)), { recursive: true, mode: 448 });
3165
+ import_fs10.default.mkdirSync(import_path7.default.join(staging, "fd", String(i)), { recursive: true, mode: 448 });
2078
3166
  }
2079
3167
  const workKey = import_crypto2.default.randomBytes(16);
2080
3168
  const derived = this.deriveRootKey(components, salt);
@@ -2084,14 +3172,14 @@ var SignService = class {
2084
3172
  this.writeMaterialFile(import_path7.default.join(staging, "fd", String(i)), Buffer.from(part));
2085
3173
  });
2086
3174
  try {
2087
- import_fs9.default.renameSync(staging, materialDir);
3175
+ import_fs10.default.renameSync(staging, materialDir);
2088
3176
  } catch (err) {
2089
- import_fs9.default.rmSync(staging, { recursive: true, force: true });
2090
- if (!import_fs9.default.existsSync(materialDir)) throw err;
3177
+ import_fs10.default.rmSync(staging, { recursive: true, force: true });
3178
+ if (!import_fs10.default.existsSync(materialDir)) throw err;
2091
3179
  }
2092
3180
  }
2093
3181
  static writeMaterialFile(dir, data) {
2094
- import_fs9.default.writeFileSync(import_path7.default.join(dir, import_crypto2.default.randomBytes(16).toString("hex")), data, { mode: 384 });
3182
+ import_fs10.default.writeFileSync(import_path7.default.join(dir, import_crypto2.default.randomBytes(16).toString("hex")), data, { mode: 384 });
2095
3183
  }
2096
3184
  /**
2097
3185
  * 使用与 devecocli / hvigor 相同的 AES-128-GCM 密钥加密密码,
@@ -2121,11 +3209,11 @@ var SignService = class {
2121
3209
  */
2122
3210
  static encryptPasswordBeside(password, p12Path, configDir) {
2123
3211
  const storeFile = import_path7.default.resolve(p12Path);
2124
- if (!import_fs9.default.existsSync(storeFile) || !import_fs9.default.statSync(storeFile).isFile()) {
3212
+ if (!import_fs10.default.existsSync(storeFile) || !import_fs10.default.statSync(storeFile).isFile()) {
2125
3213
  throw new Error(`p12 not found: ${storeFile}`);
2126
3214
  }
2127
3215
  const bundleDir = import_path7.default.dirname(storeFile);
2128
- const dir = import_fs9.default.existsSync(import_path7.default.join(bundleDir, "material")) ? bundleDir : this.resolveOhosConfigDir(configDir);
3216
+ const dir = import_fs10.default.existsSync(import_path7.default.join(bundleDir, "material")) ? bundleDir : this.resolveOhosConfigDir(configDir);
2129
3217
  const encrypted = this.encryptPassword(password, dir);
2130
3218
  const materialPath = this.placeMaterialBesideStore(bundleDir, dir);
2131
3219
  if (!materialPath) {
@@ -2143,10 +3231,10 @@ var SignService = class {
2143
3231
  }
2144
3232
  static readReleaseSigningCerts() {
2145
3233
  const file = this.releaseSigningIndexPath();
2146
- if (!import_fs9.default.existsSync(file)) return [];
3234
+ if (!import_fs10.default.existsSync(file)) return [];
2147
3235
  let parsed;
2148
3236
  try {
2149
- parsed = JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
3237
+ parsed = JSON.parse(import_fs10.default.readFileSync(file, "utf8"));
2150
3238
  } catch (err) {
2151
3239
  throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0 ${file}`, { cause: err });
2152
3240
  }
@@ -2158,20 +3246,20 @@ var SignService = class {
2158
3246
  }
2159
3247
  static writeReleaseSigningCerts(certs) {
2160
3248
  const root = this.resolveReleaseSigningRoot();
2161
- import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
3249
+ import_fs10.default.mkdirSync(root, { recursive: true, mode: 448 });
2162
3250
  const file = this.releaseSigningIndexPath();
2163
3251
  const tmp = import_path7.default.join(root, `.index-${import_crypto2.default.randomBytes(8).toString("hex")}.json`);
2164
- import_fs9.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
3252
+ import_fs10.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
2165
3253
  `, { mode: 384 });
2166
3254
  try {
2167
- if (import_fs9.default.existsSync(file)) import_fs9.default.rmSync(file);
2168
- import_fs9.default.renameSync(tmp, file);
3255
+ if (import_fs10.default.existsSync(file)) import_fs10.default.rmSync(file);
3256
+ import_fs10.default.renameSync(tmp, file);
2169
3257
  } catch (err) {
2170
3258
  try {
2171
- import_fs9.default.copyFileSync(tmp, file);
2172
- import_fs9.default.rmSync(tmp, { force: true });
3259
+ import_fs10.default.copyFileSync(tmp, file);
3260
+ import_fs10.default.rmSync(tmp, { force: true });
2173
3261
  } catch {
2174
- import_fs9.default.rmSync(tmp, { force: true });
3262
+ import_fs10.default.rmSync(tmp, { force: true });
2175
3263
  throw err;
2176
3264
  }
2177
3265
  }
@@ -2184,7 +3272,7 @@ var SignService = class {
2184
3272
  const rootDir = this.resolveReleaseSigningRoot();
2185
3273
  const certs = this.readReleaseSigningCerts().map((entry) => ({
2186
3274
  ...entry,
2187
- p12Exists: !!entry.p12Path && import_fs9.default.existsSync(entry.p12Path) && import_fs9.default.statSync(entry.p12Path).isFile()
3275
+ p12Exists: !!entry.p12Path && import_fs10.default.existsSync(entry.p12Path) && import_fs10.default.statSync(entry.p12Path).isFile()
2188
3276
  }));
2189
3277
  return { rootDir, certs };
2190
3278
  }
@@ -2216,7 +3304,7 @@ var SignService = class {
2216
3304
  }
2217
3305
  }
2218
3306
  const sourceP12 = import_path7.default.resolve(options.p12Path);
2219
- if (!import_fs9.default.existsSync(sourceP12) || !import_fs9.default.statSync(sourceP12).isFile()) {
3307
+ if (!import_fs10.default.existsSync(sourceP12) || !import_fs10.default.statSync(sourceP12).isFile()) {
2220
3308
  throw new Error(`p12 not found: ${sourceP12}`);
2221
3309
  }
2222
3310
  const root = this.resolveReleaseSigningRoot();
@@ -2224,38 +3312,38 @@ var SignService = class {
2224
3312
  const sourceDir = import_path7.default.dirname(sourceP12);
2225
3313
  const sourceMaterial = import_path7.default.join(sourceDir, "material");
2226
3314
  const sameDir = import_path7.default.resolve(sourceDir) === import_path7.default.resolve(destDir);
2227
- const materialReady = import_fs9.default.existsSync(import_path7.default.join(sameDir ? destDir : sourceDir, "material")) || import_fs9.default.existsSync(import_path7.default.join(destDir, "material"));
3315
+ const materialReady = import_fs10.default.existsSync(import_path7.default.join(sameDir ? destDir : sourceDir, "material")) || import_fs10.default.existsSync(import_path7.default.join(destDir, "material"));
2228
3316
  if (!hasPwd && !materialReady) {
2229
3317
  throw new Error("\u4FDD\u5B58\u5DF2\u52A0\u5BC6\u5BC6\u7801\u65F6\uFF0C.p12 \u540C\u7EA7\u5FC5\u987B\u5DF2\u6709 material/\u3002\u8BF7\u6539\u7528 --pwd\uFF0C\u6216\u8FDE\u540C material/ \u4E00\u8D77\u63D0\u4F9B\u3002");
2230
3318
  }
2231
3319
  const existing = this.readReleaseSigningCerts();
2232
3320
  const sourceRegistered = existing.some((entry) => entry.p12Path && this.isInside(entry.p12Path, sourceDir));
2233
3321
  const sourceIsDirectChild = import_path7.default.resolve(import_path7.default.dirname(sourceDir)) === import_path7.default.resolve(root);
2234
- import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
3322
+ import_fs10.default.mkdirSync(root, { recursive: true, mode: 448 });
2235
3323
  let storedP12;
2236
3324
  let removeSource;
2237
3325
  if (sameDir) {
2238
3326
  storedP12 = sourceP12;
2239
- } else if (sourceIsDirectChild && !sourceRegistered && !import_fs9.default.existsSync(destDir)) {
2240
- import_fs9.default.renameSync(sourceDir, destDir);
3327
+ } else if (sourceIsDirectChild && !sourceRegistered && !import_fs10.default.existsSync(destDir)) {
3328
+ import_fs10.default.renameSync(sourceDir, destDir);
2241
3329
  storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2242
3330
  } else {
2243
- import_fs9.default.mkdirSync(destDir, { recursive: true, mode: 448 });
3331
+ import_fs10.default.mkdirSync(destDir, { recursive: true, mode: 448 });
2244
3332
  storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2245
3333
  if (import_path7.default.resolve(storedP12) !== sourceP12) {
2246
- import_fs9.default.copyFileSync(sourceP12, storedP12);
3334
+ import_fs10.default.copyFileSync(sourceP12, storedP12);
2247
3335
  }
2248
3336
  if (sourceIsDirectChild && !sourceRegistered) removeSource = sourceDir;
2249
3337
  }
2250
3338
  const destMaterial = import_path7.default.join(destDir, "material");
2251
- if (!import_fs9.default.existsSync(destMaterial)) {
2252
- if (import_fs9.default.existsSync(sourceMaterial)) {
2253
- import_fs9.default.cpSync(sourceMaterial, destMaterial, { recursive: true, dereference: true });
3339
+ if (!import_fs10.default.existsSync(destMaterial)) {
3340
+ if (import_fs10.default.existsSync(sourceMaterial)) {
3341
+ import_fs10.default.cpSync(sourceMaterial, destMaterial, { recursive: true, dereference: true });
2254
3342
  } else {
2255
3343
  this.placeMaterialBesideStore(destDir, options.configDir);
2256
3344
  }
2257
3345
  }
2258
- if (!import_fs9.default.existsSync(destMaterial)) {
3346
+ if (!import_fs10.default.existsSync(destMaterial)) {
2259
3347
  throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${destDir}`);
2260
3348
  }
2261
3349
  const encrypted = hasPwd ? this.encryptPassword(pwd, destDir) : { keyPassword: options.keyPassword, storePassword: options.storePassword };
@@ -2269,8 +3357,8 @@ var SignService = class {
2269
3357
  materialPath: destMaterial
2270
3358
  };
2271
3359
  this.writeReleaseSigningCerts([...existing.filter((entry) => entry.certId !== certId), record]);
2272
- if (removeSource && import_fs9.default.existsSync(removeSource)) {
2273
- import_fs9.default.rmSync(removeSource, { recursive: true, force: true });
3360
+ if (removeSource && import_fs10.default.existsSync(removeSource)) {
3361
+ import_fs10.default.rmSync(removeSource, { recursive: true, force: true });
2274
3362
  }
2275
3363
  return record;
2276
3364
  }
@@ -2553,21 +3641,69 @@ var TestingService = class {
2553
3641
  }
2554
3642
  };
2555
3643
 
3644
+ // src/cli/upgrade.ts
3645
+ var import_node_child_process = require("child_process");
3646
+ var import_node_fs = require("fs");
3647
+ var import_node_path = __toESM(require("path"));
3648
+ var import_semver = require("semver");
3649
+ var CLI_PACKAGE_NAME = "connect-api-cli";
3650
+ var REGISTRY = "--registry=https://registry.npmjs.org/";
3651
+ function runNpm(args, stdio = "pipe") {
3652
+ const options = { encoding: "utf8", stdio };
3653
+ 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);
3654
+ if (result.error) throw result.error;
3655
+ if (result.status !== 0) {
3656
+ const detail = result.stderr?.trim() || `npm exited with ${result.signal || `code ${result.status}`}`;
3657
+ throw new Error(detail);
3658
+ }
3659
+ return result.stdout?.trim() ?? "";
3660
+ }
3661
+ function upgradeCli(currentVersion, packageDirectory) {
3662
+ const npmRoot = runNpm(["root", "--global"]);
3663
+ const installedDirectory = (0, import_node_fs.existsSync)(npmRoot) ? import_node_path.default.join((0, import_node_fs.realpathSync)(npmRoot), CLI_PACKAGE_NAME) : void 0;
3664
+ if (!installedDirectory || (0, import_node_fs.realpathSync)(packageDirectory) !== installedDirectory) {
3665
+ throw new Error(
3666
+ `Run upgrade from the active npm global installation. Install it with npm install -g ${CLI_PACKAGE_NAME}@latest ${REGISTRY}`
3667
+ );
3668
+ }
3669
+ const publishedVersion = JSON.parse(runNpm(["view", `${CLI_PACKAGE_NAME}@latest`, "version", "--json", REGISTRY]));
3670
+ const latestVersion = typeof publishedVersion === "string" ? (0, import_semver.valid)(publishedVersion) : null;
3671
+ if (!latestVersion) throw new Error("npm did not report a valid latest version.");
3672
+ if (!(0, import_semver.gt)(latestVersion, currentVersion)) {
3673
+ console.log(`${CLI_PACKAGE_NAME} ${currentVersion} is up to date (npm latest: ${latestVersion}).`);
3674
+ return;
3675
+ }
3676
+ console.log(`Upgrading ${CLI_PACKAGE_NAME} from ${currentVersion} to ${latestVersion}\u2026`);
3677
+ runNpm(["install", "--global", `${CLI_PACKAGE_NAME}@${latestVersion}`, REGISTRY], "inherit");
3678
+ const installed = JSON.parse((0, import_node_fs.readFileSync)(import_node_path.default.join(installedDirectory, "package.json"), "utf8"));
3679
+ if (installed.version !== latestVersion) {
3680
+ throw new Error(`Expected version ${latestVersion} after npm install, found ${installed.version ?? "unknown"}.`);
3681
+ }
3682
+ console.log(`Upgraded ${CLI_PACKAGE_NAME} to ${latestVersion}.`);
3683
+ }
3684
+
2556
3685
  // src/cli/index.ts
2557
3686
  var program = new import_commander.Command();
2558
3687
  function readCliVersion() {
2559
- if ("1.1.9") {
2560
- return "1.1.9";
3688
+ if ("1.1.11") {
3689
+ return "1.1.11";
2561
3690
  }
2562
3691
  try {
2563
3692
  const pkgPath = import_path8.default.join(__dirname, "..", "package.json");
2564
- const pkg = JSON.parse(fs9.readFileSync(pkgPath, "utf8"));
3693
+ const pkg = JSON.parse(fs11.readFileSync(pkgPath, "utf8"));
2565
3694
  if (pkg.version) return pkg.version;
2566
3695
  } catch {
2567
3696
  }
2568
3697
  return "0.0.0";
2569
3698
  }
2570
- program.name("connect-api-cli").description("HarmonyOS \u5F00\u53D1\u8005\u4E2D\u5FC3 API CLI Tool").version(readCliVersion());
3699
+ program.name(CLI_PACKAGE_NAME).description("HarmonyOS \u5F00\u53D1\u8005\u4E2D\u5FC3 API CLI Tool").version(readCliVersion());
3700
+ program.command("upgrade").description("Upgrade the npm global installation to the latest published version").action(() => {
3701
+ try {
3702
+ upgradeCli(readCliVersion(), import_path8.default.resolve(__dirname, ".."));
3703
+ } catch (error) {
3704
+ reportFailure("Upgrade failed:", error instanceof Error ? error.message : String(error));
3705
+ }
3706
+ });
2571
3707
  var authCmd = program.command("auth").description("Authentication management");
2572
3708
  authCmd.command("login").description("Login and cache token (default: local DevEco login, then browser OAuth)").action(async () => {
2573
3709
  try {
@@ -2604,12 +3740,17 @@ authCmd.command("status").description("Show current auth mode and cached token s
2604
3740
  }
2605
3741
  if (cfg.authMode === "oauth" || cfg.authMode === "deveco") {
2606
3742
  const teamId = cfg.teamId || getCachedOAuthTeamId();
2607
- console.log(`Team ID: ${teamId || "(auto on first API call; or set AGC_TEAM_ID)"}`);
3743
+ console.log(`Team ID: ${teamId || "(first team returned by the API; override with AGC_TEAM_ID)"}`);
2608
3744
  }
2609
3745
  if (status) {
2610
- const remaining = Math.max(0, Math.floor((status.expiresAt - Date.now()) / 1e3));
2611
3746
  console.log("Token cached: yes");
2612
- console.log(`Expires in: ${Math.floor(remaining / 60)}m ${remaining % 60}s`);
3747
+ const expiresAt = status.expiresAt;
3748
+ if (typeof expiresAt === "number" && Number.isFinite(expiresAt) && expiresAt > 0) {
3749
+ const remaining = Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3));
3750
+ console.log(`Expires in: ${Math.floor(remaining / 60)}m ${remaining % 60}s`);
3751
+ } else {
3752
+ console.log("Expires in: unknown");
3753
+ }
2613
3754
  const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials" || cfg.authMode === "deveco";
2614
3755
  console.log(`Auto-refresh: ${autoRefresh ? "enabled" : "n/a"}`);
2615
3756
  } else {
@@ -2626,7 +3767,16 @@ authCmd.command("logout").description("Logout and clear cached access token").ac
2626
3767
  });
2627
3768
  var publishCmd = program.command("publish").description("Publishing API commands");
2628
3769
  function readJsonFile(filePath) {
2629
- return JSON.parse(fs9.readFileSync(filePath, "utf8"));
3770
+ return JSON.parse(fs11.readFileSync(filePath, "utf8"));
3771
+ }
3772
+ function parseAgeRatingKind(appType, lang) {
3773
+ if (appType !== "app" && appType !== "game") {
3774
+ throw new Error("--app-type \u53EA\u80FD\u662F app \u6216 game");
3775
+ }
3776
+ if (lang !== "cn" && lang !== "en" && lang !== "ru") {
3777
+ throw new Error("--lang \u53EA\u80FD\u662F cn\u3001en \u6216 ru");
3778
+ }
3779
+ return { appType, lang };
2630
3780
  }
2631
3781
  publishCmd.command("app-id").description("Get App ID by package name").requiredOption("-p, --package-name <packageName>", "Package name (comma-separated, max 50)").option("--package-types <packageTypes>", "Optional package types filter").action(async (options) => {
2632
3782
  try {
@@ -2930,7 +4080,25 @@ publishCmd.command("privacy-submit").description("Submit privacy agreement for r
2930
4080
  reportFailure("Request failed:", e.message);
2931
4081
  }
2932
4082
  });
2933
- publishCmd.command("age-rating").description("Apply for age rating").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body (feedback/expectedRating/...)").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
4083
+ publishCmd.command("age-rating-capture").description("Open the official age-rating questionnaire and save its feedback for age-rating").option("--app-type <appType>", "app or game", "app").option("--lang <lang>", "Questionnaire language: cn, en, or ru", "cn").option("-o, --out <file>", "Body file consumed by age-rating", "age-rating-body.json").option("--timeout <minutes>", "Minutes to wait for the questionnaire submit", "30").option("--no-open", "Do not launch a browser; print the local page URL instead").action(async (options) => {
4084
+ try {
4085
+ const kind = parseAgeRatingKind(options.appType, options.lang);
4086
+ const minutes = Number(options.timeout);
4087
+ if (!Number.isFinite(minutes) || minutes <= 0) {
4088
+ throw new Error("--timeout \u5FC5\u987B\u662F\u5927\u4E8E 0 \u7684\u5206\u949F\u6570");
4089
+ }
4090
+ const result = await captureAgeRatingFeedback({
4091
+ ...kind,
4092
+ outFile: options.out,
4093
+ timeoutMs: minutes * 60 * 1e3,
4094
+ open: !options.noOpen
4095
+ });
4096
+ printResult(result);
4097
+ } catch (e) {
4098
+ reportFailure("Age rating capture failed:", e.message);
4099
+ }
4100
+ });
4101
+ publishCmd.command("age-rating").description("Apply for age rating using feedback captured by age-rating-capture").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--body <bodyFile>", "JSON body from age-rating-capture (feedback/ratingRule)").option("-r, --release-type <releaseType>", "Release type").option("--release-phase <releasePhase>", "Release phase").action(async (options) => {
2934
4102
  try {
2935
4103
  const body = readJsonFile(options.body);
2936
4104
  const res = await PublishService.applyAgeRating({
@@ -3093,7 +4261,7 @@ provisionCmd.command("release-save").description("\u628A\u53D1\u5E03 .p12\u3001\
3093
4261
  });
3094
4262
  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) => {
3095
4263
  try {
3096
- const csrContent = fs9.readFileSync(options.csr, "utf8");
4264
+ const csrContent = fs11.readFileSync(options.csr, "utf8");
3097
4265
  const res = await ProvisionService.createCert({
3098
4266
  csr: csrContent,
3099
4267
  certName: options.certName,
@@ -3127,7 +4295,7 @@ provisionCmd.command("cert-delete").description("Delete certificates").requiredO
3127
4295
  });
3128
4296
  provisionCmd.command("device-add").description("Add new devices").requiredOption("--devices <devicesFile>", 'Path to JSON file containing devices array [{"deviceName":"name","udid":"udid","deviceType":1}]').action(async (options) => {
3129
4297
  try {
3130
- const fileContent = fs9.readFileSync(options.devices, "utf8");
4298
+ const fileContent = fs11.readFileSync(options.devices, "utf8");
3131
4299
  const deviceList = JSON.parse(fileContent);
3132
4300
  const res = await ProvisionService.addDevice({ deviceList });
3133
4301
  printResult(res);
@@ -3250,7 +4418,7 @@ provisionCmd.command("acl-eligible").description("List eligible ACL permissions
3250
4418
  });
3251
4419
  provisionCmd.command("acl-apply").description("Apply for restricted ACL permissions").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--acls <aclsFile>", 'Path to JSON file containing ACL permissions [{"name":"name","reason":"reason"}]').option("--attachment <attachment>", "Attachment object ID").action(async (options) => {
3252
4420
  try {
3253
- const fileContent = fs9.readFileSync(options.acls, "utf8");
4421
+ const fileContent = fs11.readFileSync(options.acls, "utf8");
3254
4422
  const aclPermissionList = JSON.parse(fileContent);
3255
4423
  const req = { appId: options.appId, aclPermissionList };
3256
4424
  if (options.attachment) req.attachment = options.attachment;
@@ -3290,7 +4458,7 @@ domainCmd.command("query").description("Query domain configuration").requiredOpt
3290
4458
  });
3291
4459
  domainCmd.command("update").description("Add or update domain configuration").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("-c, --category <category>", "Category: server or business").requiredOption("--domains <domainsFile>", 'Path to JSON file containing domains array [{"type":"httpRequest","value":"https://..."}]').action(async (options) => {
3292
4460
  try {
3293
- const fileContent = fs9.readFileSync(options.domains, "utf8");
4461
+ const fileContent = fs11.readFileSync(options.domains, "utf8");
3294
4462
  const domains = JSON.parse(fileContent);
3295
4463
  const res = await DomainService.updateDomain({
3296
4464
  appId: options.appId,
@@ -3325,7 +4493,7 @@ domainCmd.command("verify-file").description("Download domain verify file").requ
3325
4493
  });
3326
4494
  domainCmd.command("pre-check").description("Pre-check business domain configuration").requiredOption("-a, --app-id <appId>", "App ID").requiredOption("--domain <domainFile>", 'Path to JSON file containing domain object {"type":"webView","value":"https://..."}').action(async (options) => {
3327
4495
  try {
3328
- const fileContent = fs9.readFileSync(options.domain, "utf8");
4496
+ const fileContent = fs11.readFileSync(options.domain, "utf8");
3329
4497
  const domain = JSON.parse(fileContent);
3330
4498
  const res = await DomainService.preCheckDomain({
3331
4499
  appId: options.appId,