connect-api-cli 1.1.10 → 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
  }
@@ -417,9 +928,9 @@ function clearOAuthTeamIdCache() {
417
928
 
418
929
  // src/core/deveco-token.ts
419
930
  var import_crypto = require("crypto");
420
- var import_fs4 = require("fs");
421
- var import_os2 = require("os");
422
- var import_path3 = require("path");
931
+ var import_fs5 = require("fs");
932
+ var import_os3 = require("os");
933
+ var import_path4 = require("path");
423
934
  var ALGORITHM = "aes-256-gcm";
424
935
  var KEY_LENGTH = 32;
425
936
  var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
@@ -433,11 +944,11 @@ function decryptAesGcm(ciphertext, key, iv, authTag) {
433
944
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
434
945
  }
435
946
  function readJson(filePath) {
436
- return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
947
+ return JSON.parse((0, import_fs5.readFileSync)(filePath, "utf8"));
437
948
  }
438
949
  function requireFile(filePath, label) {
439
950
  try {
440
- return (0, import_fs4.readFileSync)(filePath);
951
+ return (0, import_fs5.readFileSync)(filePath);
441
952
  } catch (err) {
442
953
  const code = err.code;
443
954
  if (code === "ENOENT") {
@@ -453,8 +964,8 @@ function loadKek(kekId, keysDir) {
453
964
  if (!KEK_VERSIONS.includes(kekId)) {
454
965
  throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
455
966
  }
456
- const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
457
- 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);
458
969
  if (!rootKeyPath.startsWith(keysDirBase)) {
459
970
  throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
460
971
  }
@@ -465,16 +976,16 @@ function loadKek(kekId, keysDir) {
465
976
  return kek;
466
977
  }
467
978
  function decryptToken(tokenDir, keysDir) {
468
- const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
979
+ const blob = readJson((0, import_path4.join)(tokenDir, "token.enc"));
469
980
  if (blob.algorithm !== ALGORITHM) {
470
981
  throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
471
982
  }
472
983
  if (!blob.ciphertext || !blob.iv || !blob.authTag) {
473
- throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.enc")}`);
984
+ throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.enc")}`);
474
985
  }
475
- const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
986
+ const wrapped = readJson((0, import_path4.join)(tokenDir, "token.dek"));
476
987
  if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
477
- throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.dek")}`);
988
+ throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.dek")}`);
478
989
  }
479
990
  const kek = loadKek(wrapped.kekId, keysDir);
480
991
  const dek = decryptAesGcm(
@@ -516,10 +1027,10 @@ function extractJwt(plaintext) {
516
1027
  return { jwt };
517
1028
  }
518
1029
  function configHome() {
519
- 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");
520
1031
  }
521
1032
  function candidatesFor(source) {
522
- const home = (0, import_os2.homedir)();
1033
+ const home = (0, import_os3.homedir)();
523
1034
  if (CLI_SOURCE_ALIASES.includes(source)) {
524
1035
  if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
525
1036
  return candidatesFor("deveco-code").map((c) => ({
@@ -531,8 +1042,8 @@ function candidatesFor(source) {
531
1042
  return [
532
1043
  {
533
1044
  source,
534
- tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
535
- keysDir: (0, import_path3.join)(home, ".local", "share", "deveco-cli", "keys"),
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"),
536
1047
  via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
537
1048
  }
538
1049
  ];
@@ -540,31 +1051,31 @@ function candidatesFor(source) {
540
1051
  const appName = SOURCE_APP_NAMES[source];
541
1052
  const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
542
1053
  if (source === "deveco-code" && viaEnv) {
543
- const tokenDir = (0, import_path3.resolve)(viaEnv);
544
- return [{ source, tokenDir, keysDir: (0, import_path3.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
1054
+ const tokenDir = (0, import_path4.resolve)(viaEnv);
1055
+ return [{ source, tokenDir, keysDir: (0, import_path4.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
545
1056
  }
546
1057
  let dirs;
547
1058
  if (process.platform === "win32") {
548
- const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
549
- dirs = [(0, import_path3.join)(appData, appName), (0, import_path3.join)(home, ".config", appName)];
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)];
550
1061
  } else if (process.platform === "darwin") {
551
1062
  dirs = [
552
- (0, import_path3.join)(configHome(), appName),
553
- (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)
554
1065
  ];
555
1066
  } else {
556
- dirs = [(0, import_path3.join)(configHome(), appName)];
1067
+ dirs = [(0, import_path4.join)(configHome(), appName)];
557
1068
  }
558
1069
  return dirs.map((tokenDir) => ({
559
1070
  source,
560
1071
  tokenDir,
561
- keysDir: (0, import_path3.join)(tokenDir, "keys"),
1072
+ keysDir: (0, import_path4.join)(tokenDir, "keys"),
562
1073
  via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
563
1074
  }));
564
1075
  }
565
1076
  function resolveLocation(source) {
566
1077
  const candidates = candidatesFor(source);
567
- 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")));
568
1079
  if (hit) {
569
1080
  return hit;
570
1081
  }
@@ -575,59 +1086,220 @@ ${tried}`
575
1086
  );
576
1087
  }
577
1088
  function loadDevecoLocalToken(source, authDir) {
578
- const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path3.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
1089
+ const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path4.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
579
1090
  const plaintext = decryptToken(location.tokenDir, location.keysDir);
580
1091
  const { jwt, expMs } = extractJwt(plaintext);
581
1092
  return { jwt, expMs, location };
582
1093
  }
583
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
+
584
1196
  // src/core/auth-mgr.ts
585
- var crypto2 = __toESM(require("crypto"));
1197
+ var crypto3 = __toESM(require("crypto"));
586
1198
  var http = __toESM(require("http"));
587
- var import_child_process = require("child_process");
588
- var import_fs5 = __toESM(require("fs"));
589
- var import_path4 = __toESM(require("path"));
590
- var import_os3 = __toESM(require("os"));
1199
+ var import_child_process2 = require("child_process");
1200
+ var import_fs6 = __toESM(require("fs"));
591
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
+ }
592
1243
  var AuthManager = class {
593
- static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
1244
+ /** 并发的 OAuth 登录共用同一次浏览器授权。 */
594
1245
  static pendingOAuthLogin;
1246
+ /** 并发请求共用一次刷新,避免同时打刷新接口或互相清缓存。 */
1247
+ static oauthRefreshInFlight = null;
595
1248
  /**
596
1249
  * 获取当前生效的 access token,并具备自动刷新能力:
597
- * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
1250
+ * - OAuth:未过期,或没有过期时间时,直接用缓存。过期且有 refreshToken 才刷新。
1251
+ * 请求路径不打开浏览器;需要重新授权时抛错,由 `auth login` 或 DevEco 降级处理。
598
1252
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
599
1253
  * - deveco:过期后重新解密本地登录态并 refresh 换取
600
1254
  *
601
- * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
1255
+ * force 跳过缓存(供 401 重试使用)。OAuth 在 force 时只走 refreshToken。
602
1256
  */
603
1257
  static async getAccessToken(force = false) {
604
1258
  const { config: config2, cache } = this.getStatus();
605
- return this.getToken(config2, cache, force);
606
- }
607
- static async getToken(cfg, cache, force = false) {
608
- if (!force && cache && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
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) {
609
1263
  return cache.accessToken;
610
1264
  }
611
- 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) {
612
1288
  try {
613
- const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
614
- const expiresAt = Date.now() + refreshed.expireTime * 1e3;
615
- this.writeCache({
616
- accessToken: refreshed.accessToken,
617
- expiresAt,
618
- clientId: cfg.clientId,
619
- domain: cfg.domain,
620
- authMode: cfg.authMode,
621
- refreshToken: cache.refreshToken
622
- // 刷新接口不返回新 refreshToken,沿用旧值
623
- });
624
- return refreshed.accessToken;
1289
+ return await this.refreshCachedOAuth(cfg, cache);
625
1290
  } catch (e) {
626
- console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
627
- this.clearCache();
1291
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache.accessToken && !interactive) {
1292
+ return cache.accessToken;
1293
+ }
1294
+ if (!interactive) throw e;
628
1295
  }
1296
+ } else if (!interactive) {
1297
+ throw new Error(NOT_LOGGED_IN);
629
1298
  }
630
- return this.acquire(cfg);
1299
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
1300
+ this.pendingOAuthLogin = void 0;
1301
+ });
1302
+ return this.pendingOAuthLogin;
631
1303
  }
632
1304
  /** 登录入口:按当前认证模式获取并缓存 token */
633
1305
  static async login() {
@@ -637,10 +1309,8 @@ var AuthManager = class {
637
1309
  /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
638
1310
  static async acquire(cfg) {
639
1311
  if (cfg.authMode === "oauth") {
640
- this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
641
- this.pendingOAuthLogin = void 0;
642
- });
643
- return this.pendingOAuthLogin;
1312
+ const cache = this.matchingCache(cfg, this.readCache());
1313
+ return this.getOAuthAccessToken(cfg, cache, false, true);
644
1314
  }
645
1315
  if (cfg.authMode === "deveco") {
646
1316
  try {
@@ -650,7 +1320,7 @@ var AuthManager = class {
650
1320
  const oauthConfig = getConfig("oauth");
651
1321
  const cache = this.matchingCache(oauthConfig, this.readCache());
652
1322
  console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
653
- return this.getToken(oauthConfig, cache);
1323
+ return this.getOAuthAccessToken(oauthConfig, cache, false, true);
654
1324
  }
655
1325
  }
656
1326
  if (cfg.authMode === "service_account") {
@@ -681,51 +1351,68 @@ var AuthManager = class {
681
1351
  }
682
1352
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
683
1353
  }
684
- /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
1354
+ /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器。同一进程只开一次。 */
685
1355
  static loginOAuth(cfg) {
686
- return new Promise((resolve2, reject) => {
1356
+ return new Promise((resolve3, reject) => {
687
1357
  const redirectUri = cfg.oauth.redirectUri;
688
1358
  const port = Number(new URL(redirectUri).port || 80);
689
- const state = crypto2.randomBytes(32).toString("hex");
690
- 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) => {
691
1370
  try {
692
- 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"}`);
693
1372
  const code = url.searchParams.get("code");
694
1373
  const returnedState = url.searchParams.get("state");
695
- if (!code || returnedState !== state) {
696
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
697
- 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));
698
1384
  return;
699
1385
  }
700
1386
  const token = await AuthService.getOAuthToken(code, redirectUri);
701
- const expiresAt = Date.now() + token.expireTime * 1e3;
702
1387
  clearOAuthTeamIdCache();
703
1388
  this.writeCache({
704
1389
  accessToken: token.accessToken,
705
- expiresAt,
1390
+ expiresAt: resolveExpiresAt(token.expireTime),
706
1391
  clientId: cfg.clientId,
707
1392
  domain: cfg.domain,
708
1393
  authMode: cfg.authMode,
709
1394
  refreshToken: token.refreshToken
710
1395
  });
711
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
712
- res.end('<!DOCTYPE html><html><body style="font-family:sans-serif;padding:40px;text-align:center"><h2>\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3</h2></body></html>');
713
- server.close();
714
- resolve2(token.accessToken);
1396
+ sendLoginPage(res, "success");
1397
+ finish(void 0, token.accessToken);
715
1398
  } catch (err) {
716
- server.close();
717
- 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));
718
1402
  }
719
1403
  });
720
1404
  server.on("error", (err) => {
721
- server.close();
722
- 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);
723
1410
  });
724
1411
  server.listen(port, () => {
725
1412
  const authUrl = AuthService.buildAuthUrl(state);
726
1413
  console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
727
1414
  console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
728
- openBrowser(authUrl);
1415
+ launchBrowser(authUrl);
729
1416
  });
730
1417
  });
731
1418
  }
@@ -762,53 +1449,458 @@ var AuthManager = class {
762
1449
  static matchingCache(cfg, cache) {
763
1450
  return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
764
1451
  }
765
- 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) {
766
1461
  try {
767
- if (import_fs5.default.existsSync(this.cacheFile)) {
768
- const data = readPrivateFile(this.cacheFile);
769
- return JSON.parse(data);
770
- }
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;
771
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;
772
1481
  }
773
- 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;
774
1488
  }
775
1489
  static writeCache(cache) {
776
- try {
777
- writePrivateFile(this.cacheFile, JSON.stringify(cache, null, 2));
778
- } 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;
779
1496
  }
1497
+ writeVault(tokenFilePath(), next);
780
1498
  }
781
1499
  /**
782
1500
  * 清除缓存的 Token(登出)
783
1501
  */
784
1502
  static clearCache() {
785
1503
  clearOAuthTeamIdCache();
786
- try {
787
- if (import_fs5.default.existsSync(this.cacheFile)) {
788
- import_fs5.default.unlinkSync(this.cacheFile);
789
- return true;
790
- }
791
- return false;
792
- } catch (e) {
793
- return false;
794
- }
1504
+ return clearVault(tokenFilePath());
795
1505
  }
796
1506
  };
797
- function openBrowser(url) {
798
- const platform = process.platform;
799
- const cmd = platform === "darwin" ? "open" : platform === "win32" ? 'start ""' : "xdg-open";
800
- (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) => {
801
1517
  if (err) {
802
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");
803
1519
  }
804
1520
  });
805
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
+ }
806
1898
 
807
1899
  // src/core/http.ts
808
1900
  var import_axios3 = __toESM(require("axios"));
809
1901
 
810
1902
  // src/core/request-source.ts
811
- var import_fs6 = __toESM(require("fs"));
1903
+ var import_fs7 = __toESM(require("fs"));
812
1904
  var import_path5 = __toESM(require("path"));
813
1905
  var REQUEST_SOURCE_HEADER = "Request-Source";
814
1906
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
@@ -949,7 +2041,7 @@ function getRequestSource() {
949
2041
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
950
2042
  }
951
2043
  function readVersion() {
952
- const fromBuild = injected(true ? "1.1.10" : void 0);
2044
+ const fromBuild = injected(true ? "1.1.11" : void 0);
953
2045
  if (fromBuild) return fromBuild;
954
2046
  const candidates = [
955
2047
  import_path5.default.join(__dirname, "..", "..", "package.json"),
@@ -957,7 +2049,7 @@ function readVersion() {
957
2049
  ];
958
2050
  for (const pkgPath of candidates) {
959
2051
  try {
960
- const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
2052
+ const pkg = JSON.parse(import_fs7.default.readFileSync(pkgPath, "utf8"));
961
2053
  if (pkg.version) return pkg.version;
962
2054
  } catch {
963
2055
  }
@@ -1051,7 +2143,7 @@ connectApiClient.interceptors.response.use(
1051
2143
  original._retry = true;
1052
2144
  try {
1053
2145
  const cfg = getConfig();
1054
- const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
2146
+ const newToken = await AuthManager.getAccessToken(true);
1055
2147
  if (!original.headers) {
1056
2148
  original.headers = {};
1057
2149
  }
@@ -1059,6 +2151,10 @@ connectApiClient.interceptors.response.use(
1059
2151
  if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1060
2152
  return connectApiClient(original);
1061
2153
  } catch (e) {
2154
+ if (e instanceof Error && e.message) {
2155
+ err.message = `${err.message}
2156
+ ${e.message}`;
2157
+ }
1062
2158
  return Promise.reject(err);
1063
2159
  }
1064
2160
  }
@@ -1531,7 +2627,7 @@ var ProvisionService = class {
1531
2627
 
1532
2628
  // src/services/upload.ts
1533
2629
  var import_axios4 = __toESM(require("axios"));
1534
- var import_fs7 = __toESM(require("fs"));
2630
+ var import_fs8 = __toESM(require("fs"));
1535
2631
  var import_path6 = __toESM(require("path"));
1536
2632
  function pickObjectId(res) {
1537
2633
  return res.urlInfo?.objectId || res.objectId;
@@ -1571,7 +2667,7 @@ var UploadService = class {
1571
2667
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1572
2668
  */
1573
2669
  static async uploadFile(options) {
1574
- const stat = import_fs7.default.statSync(options.filePath);
2670
+ const stat = import_fs8.default.statSync(options.filePath);
1575
2671
  const fileName = import_path6.default.basename(options.filePath) || "unknown";
1576
2672
  if (stat.size < 5 * 1024 * 1024) {
1577
2673
  return this.uploadSingleFile(options, fileName, stat.size);
@@ -1613,7 +2709,7 @@ var UploadService = class {
1613
2709
  );
1614
2710
  }
1615
2711
  const { url, headers } = urlRes.urlInfo;
1616
- const fileStream = import_fs7.default.createReadStream(options.filePath);
2712
+ const fileStream = import_fs8.default.createReadStream(options.filePath);
1617
2713
  await import_axios4.default.put(url, fileStream, {
1618
2714
  headers: this.buildObsPutHeaders(headers, contentLength),
1619
2715
  maxBodyLength: Infinity,
@@ -1654,7 +2750,7 @@ var UploadService = class {
1654
2750
  if (!uploadInfoMap) {
1655
2751
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1656
2752
  }
1657
- const fd = import_fs7.default.openSync(options.filePath, "r");
2753
+ const fd = import_fs8.default.openSync(options.filePath, "r");
1658
2754
  const composeReqBody = {};
1659
2755
  for (let i = 1; i <= partsCount; i++) {
1660
2756
  const propKey = `additionalProp${i}`;
@@ -1663,7 +2759,7 @@ var UploadService = class {
1663
2759
  const end = Math.min(start + partSize, fileSize);
1664
2760
  const length = end - start;
1665
2761
  const buffer = Buffer.alloc(length);
1666
- import_fs7.default.readSync(fd, buffer, 0, length, start);
2762
+ import_fs8.default.readSync(fd, buffer, 0, length, start);
1667
2763
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1668
2764
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1669
2765
  maxBodyLength: Infinity,
@@ -1675,7 +2771,7 @@ var UploadService = class {
1675
2771
  etag
1676
2772
  };
1677
2773
  }
1678
- import_fs7.default.closeSync(fd);
2774
+ import_fs8.default.closeSync(fd);
1679
2775
  await this.composeMultipart({
1680
2776
  objectId,
1681
2777
  nspUploadId,
@@ -1686,7 +2782,7 @@ var UploadService = class {
1686
2782
  };
1687
2783
 
1688
2784
  // src/services/domain.ts
1689
- var import_fs8 = __toESM(require("fs"));
2785
+ var import_fs9 = __toESM(require("fs"));
1690
2786
  var DomainService = class {
1691
2787
  /**
1692
2788
  * 查询元服务的域名配置信息
@@ -1738,8 +2834,8 @@ var DomainService = class {
1738
2834
  responseType: "stream"
1739
2835
  }
1740
2836
  );
1741
- return new Promise((resolve2, reject) => {
1742
- const writer = import_fs8.default.createWriteStream(outputPath);
2837
+ return new Promise((resolve3, reject) => {
2838
+ const writer = import_fs9.default.createWriteStream(outputPath);
1743
2839
  response.data.pipe(writer);
1744
2840
  let error = null;
1745
2841
  writer.on("error", (err) => {
@@ -1749,7 +2845,7 @@ var DomainService = class {
1749
2845
  });
1750
2846
  writer.on("close", () => {
1751
2847
  if (!error) {
1752
- resolve2();
2848
+ resolve3();
1753
2849
  }
1754
2850
  });
1755
2851
  });
@@ -1770,10 +2866,10 @@ var DomainService = class {
1770
2866
  };
1771
2867
 
1772
2868
  // src/services/sign.ts
1773
- var import_fs9 = __toESM(require("fs"));
2869
+ var import_fs10 = __toESM(require("fs"));
1774
2870
  var import_os4 = __toESM(require("os"));
1775
2871
  var import_path7 = __toESM(require("path"));
1776
- var import_child_process2 = require("child_process");
2872
+ var import_child_process4 = require("child_process");
1777
2873
  var import_crypto2 = __toESM(require("crypto"));
1778
2874
  var DEFAULT_SIGN_OUT_DIR = ".certs";
1779
2875
  var SIGN_FILE_PREFIX = {
@@ -1829,8 +2925,8 @@ var SignService = class {
1829
2925
  */
1830
2926
  static resolveSignTool(sdkPath) {
1831
2927
  const { jar, native } = this.signToolCandidates(sdkPath);
1832
- if (import_fs9.default.existsSync(jar)) return { mode: "jar", path: jar };
1833
- 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 };
1834
2930
  return void 0;
1835
2931
  }
1836
2932
  static async createSignP12AndCsr(options) {
@@ -1856,18 +2952,18 @@ var SignService = class {
1856
2952
  throw new Error(`hap-sign-tool not found at ${jar} or ${native}`);
1857
2953
  }
1858
2954
  const { rootDir, bundleDir, filename } = this.resolveSignOutputLayout(options);
1859
- const createdBundleDir = !import_fs9.default.existsSync(bundleDir);
1860
- if (!import_fs9.default.existsSync(rootDir)) {
1861
- 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 });
1862
2958
  }
1863
- import_fs9.default.mkdirSync(bundleDir, { recursive: true });
2959
+ import_fs10.default.mkdirSync(bundleDir, { recursive: true });
1864
2960
  const p12FilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "p12"));
1865
2961
  const csrFilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "csr"));
1866
2962
  const alias = options.alias;
1867
2963
  try {
1868
2964
  this.doCreateSignFileP12(javaPath, signTool, alias, pwd, p12FilePath);
1869
2965
  this.doCreateSignFileCsr(javaPath, signTool, alias, pwd, p12FilePath, csrFilePath);
1870
- const csrContent = import_fs9.default.readFileSync(csrFilePath, "utf8");
2966
+ const csrContent = import_fs10.default.readFileSync(csrFilePath, "utf8");
1871
2967
  const materialPath = this.placeMaterialBesideStore(bundleDir);
1872
2968
  return {
1873
2969
  alias,
@@ -1883,7 +2979,7 @@ var SignService = class {
1883
2979
  };
1884
2980
  } catch (err) {
1885
2981
  if (createdBundleDir) {
1886
- import_fs9.default.rmSync(bundleDir, { recursive: true, force: true });
2982
+ import_fs10.default.rmSync(bundleDir, { recursive: true, force: true });
1887
2983
  }
1888
2984
  throw err;
1889
2985
  }
@@ -1906,14 +3002,14 @@ var SignService = class {
1906
3002
  */
1907
3003
  static placeMaterialBesideStore(bundleDir, configDir) {
1908
3004
  const dest = import_path7.default.join(bundleDir, "material");
1909
- if (import_fs9.default.existsSync(dest)) {
3005
+ if (import_fs10.default.existsSync(dest)) {
1910
3006
  return dest;
1911
3007
  }
1912
3008
  const src = this.ensureMaterial(this.resolveOhosConfigDir(configDir));
1913
3009
  try {
1914
- import_fs9.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
3010
+ import_fs10.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1915
3011
  } catch {
1916
- import_fs9.default.cpSync(src, dest, { recursive: true });
3012
+ import_fs10.default.cpSync(src, dest, { recursive: true });
1917
3013
  }
1918
3014
  return dest;
1919
3015
  }
@@ -1931,12 +3027,12 @@ var SignService = class {
1931
3027
  static runSignTool(javaPath, tool, toolArgs) {
1932
3028
  if (tool.mode === "native") {
1933
3029
  console.error(`Executing: ${tool.path} ${this.maskArgs(toolArgs)}`);
1934
- (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"] });
1935
3031
  return;
1936
3032
  }
1937
3033
  const args = ["-jar", tool.path, ...toolArgs];
1938
3034
  console.error(`Executing: ${javaPath} ${this.maskArgs(args)}`);
1939
- (0, import_child_process2.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
3035
+ (0, import_child_process4.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
1940
3036
  }
1941
3037
  static doCreateSignFileP12(javaPath, tool, alias, pwd, outFilePath) {
1942
3038
  const args = [
@@ -1978,12 +3074,12 @@ var SignService = class {
1978
3074
  }
1979
3075
  static COMPONENT = new Int8Array([49, 243, 9, 115, 214, 175, 91, 184, 211, 190, 177, 88, 101, 131, 192, 119]);
1980
3076
  static readDirBytes(dirPath) {
1981
- const entries = import_fs9.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1982
- return new Int8Array(import_fs9.default.readFileSync(import_path7.default.resolve(dirPath, entries[0])));
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])));
1983
3079
  }
1984
3080
  static readFd(materialPath) {
1985
3081
  const fdDir = import_path7.default.resolve(materialPath, "fd");
1986
- return import_fs9.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
3082
+ return import_fs10.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
1987
3083
  }
1988
3084
  static xorBuffers(a, b) {
1989
3085
  const result = new Int8Array(a.byteLength);
@@ -2051,22 +3147,22 @@ var SignService = class {
2051
3147
  */
2052
3148
  static ensureMaterial(configDir) {
2053
3149
  const materialDir = import_path7.default.resolve(configDir, "material");
2054
- if (!import_fs9.default.existsSync(materialDir)) this.generateMaterial(configDir);
3150
+ if (!import_fs10.default.existsSync(materialDir)) this.generateMaterial(configDir);
2055
3151
  return materialDir;
2056
3152
  }
2057
3153
  static generateMaterial(configDir) {
2058
3154
  const materialDir = import_path7.default.resolve(configDir, "material");
2059
- if (import_fs9.default.existsSync(materialDir)) return;
2060
- import_fs9.default.mkdirSync(configDir, { recursive: true, mode: 448 });
3155
+ if (import_fs10.default.existsSync(materialDir)) return;
3156
+ import_fs10.default.mkdirSync(configDir, { recursive: true, mode: 448 });
2061
3157
  const staging = import_path7.default.join(configDir, `.material-${import_crypto2.default.randomBytes(8).toString("hex")}`);
2062
3158
  const acDir = import_path7.default.join(staging, "ac");
2063
3159
  const ceDir = import_path7.default.join(staging, "ce");
2064
- import_fs9.default.mkdirSync(acDir, { recursive: true, mode: 448 });
2065
- import_fs9.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
3160
+ import_fs10.default.mkdirSync(acDir, { recursive: true, mode: 448 });
3161
+ import_fs10.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
2066
3162
  const salt = import_crypto2.default.randomBytes(16);
2067
3163
  const components = [0, 1, 2].map(() => new Int8Array(import_crypto2.default.randomBytes(16)));
2068
3164
  for (let i = 0; i < components.length; i++) {
2069
- 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 });
2070
3166
  }
2071
3167
  const workKey = import_crypto2.default.randomBytes(16);
2072
3168
  const derived = this.deriveRootKey(components, salt);
@@ -2076,14 +3172,14 @@ var SignService = class {
2076
3172
  this.writeMaterialFile(import_path7.default.join(staging, "fd", String(i)), Buffer.from(part));
2077
3173
  });
2078
3174
  try {
2079
- import_fs9.default.renameSync(staging, materialDir);
3175
+ import_fs10.default.renameSync(staging, materialDir);
2080
3176
  } catch (err) {
2081
- import_fs9.default.rmSync(staging, { recursive: true, force: true });
2082
- 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;
2083
3179
  }
2084
3180
  }
2085
3181
  static writeMaterialFile(dir, data) {
2086
- 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 });
2087
3183
  }
2088
3184
  /**
2089
3185
  * 使用与 devecocli / hvigor 相同的 AES-128-GCM 密钥加密密码,
@@ -2113,11 +3209,11 @@ var SignService = class {
2113
3209
  */
2114
3210
  static encryptPasswordBeside(password, p12Path, configDir) {
2115
3211
  const storeFile = import_path7.default.resolve(p12Path);
2116
- 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()) {
2117
3213
  throw new Error(`p12 not found: ${storeFile}`);
2118
3214
  }
2119
3215
  const bundleDir = import_path7.default.dirname(storeFile);
2120
- 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);
2121
3217
  const encrypted = this.encryptPassword(password, dir);
2122
3218
  const materialPath = this.placeMaterialBesideStore(bundleDir, dir);
2123
3219
  if (!materialPath) {
@@ -2135,10 +3231,10 @@ var SignService = class {
2135
3231
  }
2136
3232
  static readReleaseSigningCerts() {
2137
3233
  const file = this.releaseSigningIndexPath();
2138
- if (!import_fs9.default.existsSync(file)) return [];
3234
+ if (!import_fs10.default.existsSync(file)) return [];
2139
3235
  let parsed;
2140
3236
  try {
2141
- parsed = JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
3237
+ parsed = JSON.parse(import_fs10.default.readFileSync(file, "utf8"));
2142
3238
  } catch (err) {
2143
3239
  throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0 ${file}`, { cause: err });
2144
3240
  }
@@ -2150,20 +3246,20 @@ var SignService = class {
2150
3246
  }
2151
3247
  static writeReleaseSigningCerts(certs) {
2152
3248
  const root = this.resolveReleaseSigningRoot();
2153
- import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
3249
+ import_fs10.default.mkdirSync(root, { recursive: true, mode: 448 });
2154
3250
  const file = this.releaseSigningIndexPath();
2155
3251
  const tmp = import_path7.default.join(root, `.index-${import_crypto2.default.randomBytes(8).toString("hex")}.json`);
2156
- import_fs9.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
3252
+ import_fs10.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
2157
3253
  `, { mode: 384 });
2158
3254
  try {
2159
- if (import_fs9.default.existsSync(file)) import_fs9.default.rmSync(file);
2160
- 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);
2161
3257
  } catch (err) {
2162
3258
  try {
2163
- import_fs9.default.copyFileSync(tmp, file);
2164
- import_fs9.default.rmSync(tmp, { force: true });
3259
+ import_fs10.default.copyFileSync(tmp, file);
3260
+ import_fs10.default.rmSync(tmp, { force: true });
2165
3261
  } catch {
2166
- import_fs9.default.rmSync(tmp, { force: true });
3262
+ import_fs10.default.rmSync(tmp, { force: true });
2167
3263
  throw err;
2168
3264
  }
2169
3265
  }
@@ -2176,7 +3272,7 @@ var SignService = class {
2176
3272
  const rootDir = this.resolveReleaseSigningRoot();
2177
3273
  const certs = this.readReleaseSigningCerts().map((entry) => ({
2178
3274
  ...entry,
2179
- 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()
2180
3276
  }));
2181
3277
  return { rootDir, certs };
2182
3278
  }
@@ -2208,7 +3304,7 @@ var SignService = class {
2208
3304
  }
2209
3305
  }
2210
3306
  const sourceP12 = import_path7.default.resolve(options.p12Path);
2211
- 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()) {
2212
3308
  throw new Error(`p12 not found: ${sourceP12}`);
2213
3309
  }
2214
3310
  const root = this.resolveReleaseSigningRoot();
@@ -2216,38 +3312,38 @@ var SignService = class {
2216
3312
  const sourceDir = import_path7.default.dirname(sourceP12);
2217
3313
  const sourceMaterial = import_path7.default.join(sourceDir, "material");
2218
3314
  const sameDir = import_path7.default.resolve(sourceDir) === import_path7.default.resolve(destDir);
2219
- const materialReady = import_fs9.default.existsSync(import_path7.default.join(sameDir ? destDir : sourceDir, "material")) || import_fs9.default.existsSync(import_path7.default.join(destDir, "material"));
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"));
2220
3316
  if (!hasPwd && !materialReady) {
2221
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");
2222
3318
  }
2223
3319
  const existing = this.readReleaseSigningCerts();
2224
3320
  const sourceRegistered = existing.some((entry) => entry.p12Path && this.isInside(entry.p12Path, sourceDir));
2225
3321
  const sourceIsDirectChild = import_path7.default.resolve(import_path7.default.dirname(sourceDir)) === import_path7.default.resolve(root);
2226
- import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
3322
+ import_fs10.default.mkdirSync(root, { recursive: true, mode: 448 });
2227
3323
  let storedP12;
2228
3324
  let removeSource;
2229
3325
  if (sameDir) {
2230
3326
  storedP12 = sourceP12;
2231
- } else if (sourceIsDirectChild && !sourceRegistered && !import_fs9.default.existsSync(destDir)) {
2232
- import_fs9.default.renameSync(sourceDir, destDir);
3327
+ } else if (sourceIsDirectChild && !sourceRegistered && !import_fs10.default.existsSync(destDir)) {
3328
+ import_fs10.default.renameSync(sourceDir, destDir);
2233
3329
  storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2234
3330
  } else {
2235
- import_fs9.default.mkdirSync(destDir, { recursive: true, mode: 448 });
3331
+ import_fs10.default.mkdirSync(destDir, { recursive: true, mode: 448 });
2236
3332
  storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2237
3333
  if (import_path7.default.resolve(storedP12) !== sourceP12) {
2238
- import_fs9.default.copyFileSync(sourceP12, storedP12);
3334
+ import_fs10.default.copyFileSync(sourceP12, storedP12);
2239
3335
  }
2240
3336
  if (sourceIsDirectChild && !sourceRegistered) removeSource = sourceDir;
2241
3337
  }
2242
3338
  const destMaterial = import_path7.default.join(destDir, "material");
2243
- if (!import_fs9.default.existsSync(destMaterial)) {
2244
- if (import_fs9.default.existsSync(sourceMaterial)) {
2245
- import_fs9.default.cpSync(sourceMaterial, destMaterial, { recursive: true, dereference: true });
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 });
2246
3342
  } else {
2247
3343
  this.placeMaterialBesideStore(destDir, options.configDir);
2248
3344
  }
2249
3345
  }
2250
- if (!import_fs9.default.existsSync(destMaterial)) {
3346
+ if (!import_fs10.default.existsSync(destMaterial)) {
2251
3347
  throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${destDir}`);
2252
3348
  }
2253
3349
  const encrypted = hasPwd ? this.encryptPassword(pwd, destDir) : { keyPassword: options.keyPassword, storePassword: options.storePassword };
@@ -2261,8 +3357,8 @@ var SignService = class {
2261
3357
  materialPath: destMaterial
2262
3358
  };
2263
3359
  this.writeReleaseSigningCerts([...existing.filter((entry) => entry.certId !== certId), record]);
2264
- if (removeSource && import_fs9.default.existsSync(removeSource)) {
2265
- import_fs9.default.rmSync(removeSource, { recursive: true, force: true });
3360
+ if (removeSource && import_fs10.default.existsSync(removeSource)) {
3361
+ import_fs10.default.rmSync(removeSource, { recursive: true, force: true });
2266
3362
  }
2267
3363
  return record;
2268
3364
  }
@@ -2589,12 +3685,12 @@ function upgradeCli(currentVersion, packageDirectory) {
2589
3685
  // src/cli/index.ts
2590
3686
  var program = new import_commander.Command();
2591
3687
  function readCliVersion() {
2592
- if ("1.1.10") {
2593
- return "1.1.10";
3688
+ if ("1.1.11") {
3689
+ return "1.1.11";
2594
3690
  }
2595
3691
  try {
2596
3692
  const pkgPath = import_path8.default.join(__dirname, "..", "package.json");
2597
- const pkg = JSON.parse(fs9.readFileSync(pkgPath, "utf8"));
3693
+ const pkg = JSON.parse(fs11.readFileSync(pkgPath, "utf8"));
2598
3694
  if (pkg.version) return pkg.version;
2599
3695
  } catch {
2600
3696
  }
@@ -2647,9 +3743,14 @@ authCmd.command("status").description("Show current auth mode and cached token s
2647
3743
  console.log(`Team ID: ${teamId || "(first team returned by the API; override with AGC_TEAM_ID)"}`);
2648
3744
  }
2649
3745
  if (status) {
2650
- const remaining = Math.max(0, Math.floor((status.expiresAt - Date.now()) / 1e3));
2651
3746
  console.log("Token cached: yes");
2652
- 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
+ }
2653
3754
  const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials" || cfg.authMode === "deveco";
2654
3755
  console.log(`Auto-refresh: ${autoRefresh ? "enabled" : "n/a"}`);
2655
3756
  } else {
@@ -2666,7 +3767,16 @@ authCmd.command("logout").description("Logout and clear cached access token").ac
2666
3767
  });
2667
3768
  var publishCmd = program.command("publish").description("Publishing API commands");
2668
3769
  function readJsonFile(filePath) {
2669
- 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 };
2670
3780
  }
2671
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) => {
2672
3782
  try {
@@ -2970,7 +4080,25 @@ publishCmd.command("privacy-submit").description("Submit privacy agreement for r
2970
4080
  reportFailure("Request failed:", e.message);
2971
4081
  }
2972
4082
  });
2973
- 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) => {
2974
4102
  try {
2975
4103
  const body = readJsonFile(options.body);
2976
4104
  const res = await PublishService.applyAgeRating({
@@ -3133,7 +4261,7 @@ provisionCmd.command("release-save").description("\u628A\u53D1\u5E03 .p12\u3001\
3133
4261
  });
3134
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) => {
3135
4263
  try {
3136
- const csrContent = fs9.readFileSync(options.csr, "utf8");
4264
+ const csrContent = fs11.readFileSync(options.csr, "utf8");
3137
4265
  const res = await ProvisionService.createCert({
3138
4266
  csr: csrContent,
3139
4267
  certName: options.certName,
@@ -3167,7 +4295,7 @@ provisionCmd.command("cert-delete").description("Delete certificates").requiredO
3167
4295
  });
3168
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) => {
3169
4297
  try {
3170
- const fileContent = fs9.readFileSync(options.devices, "utf8");
4298
+ const fileContent = fs11.readFileSync(options.devices, "utf8");
3171
4299
  const deviceList = JSON.parse(fileContent);
3172
4300
  const res = await ProvisionService.addDevice({ deviceList });
3173
4301
  printResult(res);
@@ -3290,7 +4418,7 @@ provisionCmd.command("acl-eligible").description("List eligible ACL permissions
3290
4418
  });
3291
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) => {
3292
4420
  try {
3293
- const fileContent = fs9.readFileSync(options.acls, "utf8");
4421
+ const fileContent = fs11.readFileSync(options.acls, "utf8");
3294
4422
  const aclPermissionList = JSON.parse(fileContent);
3295
4423
  const req = { appId: options.appId, aclPermissionList };
3296
4424
  if (options.attachment) req.attachment = options.attachment;
@@ -3330,7 +4458,7 @@ domainCmd.command("query").description("Query domain configuration").requiredOpt
3330
4458
  });
3331
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) => {
3332
4460
  try {
3333
- const fileContent = fs9.readFileSync(options.domains, "utf8");
4461
+ const fileContent = fs11.readFileSync(options.domains, "utf8");
3334
4462
  const domains = JSON.parse(fileContent);
3335
4463
  const res = await DomainService.updateDomain({
3336
4464
  appId: options.appId,
@@ -3365,7 +4493,7 @@ domainCmd.command("verify-file").description("Download domain verify file").requ
3365
4493
  });
3366
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) => {
3367
4495
  try {
3368
- const fileContent = fs9.readFileSync(options.domain, "utf8");
4496
+ const fileContent = fs11.readFileSync(options.domain, "utf8");
3369
4497
  const domain = JSON.parse(fileContent);
3370
4498
  const res = await DomainService.preCheckDomain({
3371
4499
  appId: options.appId,