connect-api-cli 1.1.9 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31,12 +31,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  AuthService: () => AuthService,
34
+ OAuthRefreshRejectedError: () => OAuthRefreshRejectedError,
34
35
  ProjectService: () => ProjectService,
35
36
  ProvisionService: () => ProvisionService,
36
37
  PublishService: () => PublishService,
37
38
  UploadService: () => UploadService,
38
39
  connectApiClient: () => connectApiClient,
39
- getConfig: () => getConfig
40
+ getConfig: () => getConfig,
41
+ isDefinitiveOAuthRefreshFailure: () => isDefinitiveOAuthRefreshFailure,
42
+ normalizeOAuthToken: () => normalizeOAuthToken
40
43
  });
41
44
  module.exports = __toCommonJS(src_exports);
42
45
 
@@ -146,6 +149,44 @@ function getConfig(authMode = process.env.AGC_AUTH_MODE ?? "deveco") {
146
149
  }
147
150
 
148
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
+ }
149
190
  var SA_AUD = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
150
191
  var SA_JWT_TTL_SEC = 3600;
151
192
  var DEVECO_CHECK_URL = process.env.AGC_DEVECO_CHECK_URL || "https://cn.devecostudio.huawei.com/authrouter/auth/api/jwToken/check";
@@ -236,7 +277,8 @@ var AuthService = class {
236
277
  if (!res.data.ret || res.data.ret.code !== 0) {
237
278
  throw new Error(res.data.ret?.msg || "Authentication failed");
238
279
  }
239
- return res.data;
280
+ const token = normalizeOAuthToken(res.data);
281
+ return { ret: res.data.ret, accessToken: token.accessToken, expireTime: token.expireTime, refreshToken: token.refreshToken };
240
282
  } catch (err) {
241
283
  if (err instanceof Error && err.name === "AbortError") {
242
284
  throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
@@ -261,9 +303,15 @@ var AuthService = class {
261
303
  signal: controller.signal
262
304
  });
263
305
  if (!res.data.ret || res.data.ret.code !== 0) {
264
- throw new Error(res.data.ret?.msg || "Refresh failed");
306
+ throw new OAuthRefreshRejectedError(res.data.ret?.msg || "Refresh failed");
265
307
  }
266
- 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
+ };
267
315
  } catch (err) {
268
316
  if (err instanceof Error && err.name === "AbortError") {
269
317
  throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
@@ -321,6 +369,21 @@ function normalizePem(privateKey) {
321
369
  // src/core/http.ts
322
370
  var import_axios3 = __toESM(require("axios"));
323
371
 
372
+ // src/core/oauth-team.ts
373
+ var import_axios2 = __toESM(require("axios"));
374
+
375
+ // src/core/token-vault.ts
376
+ var crypto2 = __toESM(require("crypto"));
377
+ var import_fs4 = __toESM(require("fs"));
378
+ var import_os2 = __toESM(require("os"));
379
+ var import_path3 = __toESM(require("path"));
380
+
381
+ // src/core/key-store.ts
382
+ var import_child_process = require("child_process");
383
+ var import_fs3 = __toESM(require("fs"));
384
+ var import_os = __toESM(require("os"));
385
+ var import_path2 = __toESM(require("path"));
386
+
324
387
  // src/core/private-file.ts
325
388
  var import_fs2 = __toESM(require("fs"));
326
389
  function restrictPermissions(fd) {
@@ -346,28 +409,479 @@ function writePrivateFile(file, contents) {
346
409
  }
347
410
  }
348
411
 
412
+ // src/core/key-store.ts
413
+ var KEYCHAIN_SERVICE = "connect-api-cli";
414
+ var KEYCHAIN_ACCOUNT = "token-key";
415
+ var KEYCHAIN_SLOT = `${KEYCHAIN_SERVICE}\0${KEYCHAIN_ACCOUNT}`;
416
+ var SECRET_SLOT = "connect-api-cli\0token-key";
417
+ var unlocked = /* @__PURE__ */ new Map();
418
+ function tokenKeyPath(tokenFile) {
419
+ return import_path2.default.join(import_path2.default.dirname(tokenFile), ".connect-api-cli-token.key");
420
+ }
421
+ function forgetKeyFile(keyFile) {
422
+ unlocked.delete(cacheId("dpapi", keyFile));
423
+ unlocked.delete(cacheId("file", keyFile));
424
+ }
425
+ function createDefaultKeyStore(tokenFile) {
426
+ if (process.platform === "win32") return createDpapiKeyStore(tokenKeyPath(tokenFile));
427
+ if (process.platform === "darwin") return createKeychainKeyStore();
428
+ return createLinuxKeyStore(tokenKeyPath(tokenFile));
429
+ }
430
+ function keyStoreById(id, tokenFile) {
431
+ const keyFile = tokenKeyPath(tokenFile);
432
+ if (id === "dpapi") return createDpapiKeyStore(keyFile);
433
+ if (id === "keychain") return createKeychainKeyStore();
434
+ if (id === "secret-service") return createSecretServiceKeyStore();
435
+ if (id === "file") return createFileKeyStore(keyFile);
436
+ throw new Error(`Unknown token key protection: ${id}`);
437
+ }
438
+ function createFileKeyStore(keyFile) {
439
+ return {
440
+ id: "file",
441
+ load: () => readPrefixedKey("file", keyFile, "raw:"),
442
+ save: (key) => writePrefixedKey("file", keyFile, "raw:", key),
443
+ clear: () => removePrefixedKey("file", keyFile)
444
+ };
445
+ }
446
+ function createDpapiKeyStore(keyFile) {
447
+ return {
448
+ id: "dpapi",
449
+ load: () => {
450
+ const cached = recall("dpapi", keyFile);
451
+ if (cached) return cached;
452
+ const wrapped = readPrefixed(keyFile, "dpapi:");
453
+ if (!wrapped) return null;
454
+ const key = decodeKey(dpapi("unprotect", wrapped));
455
+ if (!key) return null;
456
+ remember("dpapi", keyFile, key);
457
+ return key;
458
+ },
459
+ save: (key) => {
460
+ assertKey(key);
461
+ writePrefixed(keyFile, "dpapi:", dpapi("protect", key.toString("base64")));
462
+ remember("dpapi", keyFile, key);
463
+ },
464
+ clear: () => removePrefixedKey("dpapi", keyFile)
465
+ };
466
+ }
467
+ function createKeychainKeyStore() {
468
+ return {
469
+ id: "keychain",
470
+ load: () => keychainLoad(),
471
+ save: (key) => keychainSave(key),
472
+ clear: () => keychainClear()
473
+ };
474
+ }
475
+ function createSecretServiceKeyStore() {
476
+ return {
477
+ id: "secret-service",
478
+ load: () => secretLookup(),
479
+ save: (key) => {
480
+ if (!secretStore(key)) {
481
+ throw new Error("Failed to store the token key in the Secret Service.");
482
+ }
483
+ },
484
+ clear: () => secretClear()
485
+ };
486
+ }
487
+ function createLinuxKeyStore(keyFile) {
488
+ const store = {
489
+ id: "file",
490
+ load() {
491
+ if (hasSecretTool()) {
492
+ const key2 = secretLookup();
493
+ if (key2) {
494
+ store.id = "secret-service";
495
+ return key2;
496
+ }
497
+ }
498
+ const key = readPrefixedKey("file", keyFile, "raw:");
499
+ if (key) store.id = "file";
500
+ return key;
501
+ },
502
+ save(key) {
503
+ if (hasSecretTool() && secretStore(key)) {
504
+ store.id = "secret-service";
505
+ removePrefixedKey("file", keyFile);
506
+ return;
507
+ }
508
+ store.id = "file";
509
+ writePrefixedKey("file", keyFile, "raw:", key);
510
+ },
511
+ clear() {
512
+ secretClear();
513
+ removePrefixedKey("file", keyFile);
514
+ }
515
+ };
516
+ return store;
517
+ }
518
+ function cacheId(id, slot) {
519
+ return `${id}\0${slot}`;
520
+ }
521
+ function remember(id, slot, key) {
522
+ unlocked.set(cacheId(id, slot), Buffer.from(key));
523
+ }
524
+ function recall(id, slot) {
525
+ const hit = unlocked.get(cacheId(id, slot));
526
+ return hit ? Buffer.from(hit) : null;
527
+ }
528
+ function forget(id, slot) {
529
+ unlocked.delete(cacheId(id, slot));
530
+ }
531
+ function assertKey(key) {
532
+ if (key.length !== 32) throw new Error("Token key must be 32 bytes");
533
+ }
534
+ function decodeKey(b64) {
535
+ const key = Buffer.from(b64, "base64");
536
+ return key.length === 32 ? key : null;
537
+ }
538
+ function readPrefixed(keyFile, prefix) {
539
+ if (!import_fs3.default.existsSync(keyFile)) return null;
540
+ const text = import_fs3.default.readFileSync(keyFile, "utf8").replace(/^\uFEFF/, "").trim();
541
+ if (!text.startsWith(prefix)) return null;
542
+ return text.slice(prefix.length);
543
+ }
544
+ function readPrefixedKey(id, keyFile, prefix) {
545
+ const cached = recall(id, keyFile);
546
+ if (cached) return cached;
547
+ const b64 = readPrefixed(keyFile, prefix);
548
+ if (!b64) return null;
549
+ const key = decodeKey(b64);
550
+ if (!key) return null;
551
+ remember(id, keyFile, key);
552
+ return key;
553
+ }
554
+ function writePrefixed(keyFile, prefix, payload) {
555
+ import_fs3.default.mkdirSync(import_path2.default.dirname(keyFile), { recursive: true });
556
+ writePrivateFile(keyFile, `${prefix}${payload}
557
+ `);
558
+ }
559
+ function writePrefixedKey(id, keyFile, prefix, key) {
560
+ assertKey(key);
561
+ writePrefixed(keyFile, prefix, key.toString("base64"));
562
+ remember(id, keyFile, key);
563
+ }
564
+ function removePrefixedKey(id, keyFile) {
565
+ forget(id, keyFile);
566
+ import_fs3.default.rmSync(keyFile, { force: true });
567
+ }
568
+ var DPAPI_SCRIPT = `
569
+ $ErrorActionPreference = 'Stop'
570
+ Add-Type -AssemblyName System.Security
571
+ $utf8 = New-Object System.Text.UTF8Encoding $false
572
+ $b64 = [System.IO.File]::ReadAllText($env:CONNECT_API_SECRET_IN).Trim()
573
+ $bytes = [System.Convert]::FromBase64String($b64)
574
+ $entropy = [System.Text.Encoding]::UTF8.GetBytes('connect-api-cli-token-v1')
575
+ $scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
576
+ if ($env:CONNECT_API_SECRET_OP -eq 'protect') {
577
+ $outBytes = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope)
578
+ } elseif ($env:CONNECT_API_SECRET_OP -eq 'unprotect') {
579
+ $outBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope)
580
+ } else {
581
+ throw 'bad op'
582
+ }
583
+ [System.IO.File]::WriteAllText($env:CONNECT_API_SECRET_OUT, [System.Convert]::ToBase64String($outBytes), $utf8)
584
+ `;
585
+ function powershellExe() {
586
+ const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
587
+ const candidate = import_path2.default.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
588
+ return import_fs3.default.existsSync(candidate) ? candidate : "powershell.exe";
589
+ }
590
+ function dpapi(op, payloadB64) {
591
+ const dir = import_fs3.default.mkdtempSync(import_path2.default.join(import_os.default.tmpdir(), "connect-api-cli-"));
592
+ const inPath = import_path2.default.join(dir, "in.txt");
593
+ const outPath = import_path2.default.join(dir, "out.txt");
594
+ try {
595
+ import_fs3.default.writeFileSync(inPath, payloadB64, { encoding: "utf8", mode: 384 });
596
+ const encoded = Buffer.from(DPAPI_SCRIPT, "utf16le").toString("base64");
597
+ try {
598
+ (0, import_child_process.execFileSync)(powershellExe(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
599
+ env: {
600
+ ...process.env,
601
+ CONNECT_API_SECRET_IN: inPath,
602
+ CONNECT_API_SECRET_OUT: outPath,
603
+ CONNECT_API_SECRET_OP: op
604
+ },
605
+ windowsHide: true,
606
+ timeout: 2e4,
607
+ stdio: ["ignore", "pipe", "pipe"],
608
+ encoding: "utf8"
609
+ });
610
+ } catch (e) {
611
+ const stderr = typeof e.stderr === "string" ? e.stderr.trim().slice(0, 400) : "";
612
+ throw new Error(`Windows DPAPI ${op} failed${stderr ? `: ${stderr}` : ""}`);
613
+ }
614
+ if (!import_fs3.default.existsSync(outPath)) throw new Error(`Windows DPAPI ${op} failed: no output`);
615
+ return import_fs3.default.readFileSync(outPath, "utf8").replace(/^\uFEFF/, "").trim();
616
+ } finally {
617
+ import_fs3.default.rmSync(dir, { recursive: true, force: true });
618
+ }
619
+ }
620
+ function keychainLoad() {
621
+ const cached = recall("keychain", KEYCHAIN_SLOT);
622
+ if (cached) return cached;
623
+ try {
624
+ const out = (0, import_child_process.execFileSync)("security", [
625
+ "find-generic-password",
626
+ "-s",
627
+ KEYCHAIN_SERVICE,
628
+ "-a",
629
+ KEYCHAIN_ACCOUNT,
630
+ "-w"
631
+ ], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
632
+ const key = decodeKey(out.trim());
633
+ if (!key) return null;
634
+ remember("keychain", KEYCHAIN_SLOT, key);
635
+ return key;
636
+ } catch (e) {
637
+ const status = e.status;
638
+ if (status === 44) return null;
639
+ throw new Error("macOS Keychain read failed");
640
+ }
641
+ }
642
+ function keychainSave(key) {
643
+ assertKey(key);
644
+ (0, import_child_process.execFileSync)("security", [
645
+ "add-generic-password",
646
+ "-U",
647
+ "-A",
648
+ "-s",
649
+ KEYCHAIN_SERVICE,
650
+ "-a",
651
+ KEYCHAIN_ACCOUNT,
652
+ "-w",
653
+ key.toString("base64")
654
+ ], { timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
655
+ remember("keychain", KEYCHAIN_SLOT, key);
656
+ }
657
+ function keychainClear() {
658
+ forget("keychain", KEYCHAIN_SLOT);
659
+ try {
660
+ (0, import_child_process.execFileSync)("security", [
661
+ "delete-generic-password",
662
+ "-s",
663
+ KEYCHAIN_SERVICE,
664
+ "-a",
665
+ KEYCHAIN_ACCOUNT
666
+ ], { timeout: 1e4, stdio: "ignore" });
667
+ } catch {
668
+ }
669
+ }
670
+ var secretToolAvailable;
671
+ function hasSecretTool() {
672
+ if (process.platform === "win32" || process.platform === "darwin") return false;
673
+ if (secretToolAvailable !== void 0) return secretToolAvailable;
674
+ const r = (0, import_child_process.spawnSync)("secret-tool", ["--version"], { stdio: "ignore" });
675
+ const missing = !!r.error && r.error.code === "ENOENT";
676
+ secretToolAvailable = !missing;
677
+ return secretToolAvailable;
678
+ }
679
+ function secretLookup() {
680
+ const cached = recall("secret-service", SECRET_SLOT);
681
+ if (cached) return cached;
682
+ const r = (0, import_child_process.spawnSync)("secret-tool", [
683
+ "lookup",
684
+ "service",
685
+ "connect-api-cli",
686
+ "username",
687
+ "token-key"
688
+ ], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
689
+ if (r.error || r.status !== 0) return null;
690
+ const key = decodeKey((r.stdout || "").trim());
691
+ if (!key) return null;
692
+ remember("secret-service", SECRET_SLOT, key);
693
+ return key;
694
+ }
695
+ function secretStore(key) {
696
+ assertKey(key);
697
+ const r = (0, import_child_process.spawnSync)("secret-tool", [
698
+ "store",
699
+ "--label=connect-api-cli token key",
700
+ "service",
701
+ "connect-api-cli",
702
+ "username",
703
+ "token-key"
704
+ ], {
705
+ input: key.toString("base64"),
706
+ encoding: "utf8",
707
+ timeout: 1e4,
708
+ stdio: ["pipe", "pipe", "pipe"]
709
+ });
710
+ if (r.status !== 0) return false;
711
+ remember("secret-service", SECRET_SLOT, key);
712
+ return true;
713
+ }
714
+ function secretClear() {
715
+ forget("secret-service", SECRET_SLOT);
716
+ (0, import_child_process.spawnSync)("secret-tool", [
717
+ "clear",
718
+ "service",
719
+ "connect-api-cli",
720
+ "username",
721
+ "token-key"
722
+ ], { stdio: "ignore", timeout: 1e4 });
723
+ }
724
+
725
+ // src/core/token-vault.ts
726
+ var KTY = "connect-api-cli-secret";
727
+ var TokenDecryptError = class extends Error {
728
+ constructor() {
729
+ super("Token cache authentication failed");
730
+ this.name = "TokenDecryptError";
731
+ }
732
+ };
733
+ function tokenFilePath() {
734
+ return import_path3.default.join(import_os2.default.homedir(), ".connect-api-cli-token.json");
735
+ }
736
+ function readVault(file, store) {
737
+ if (!import_fs4.default.existsSync(file)) return null;
738
+ let parsed;
739
+ try {
740
+ parsed = JSON.parse(readPrivateFile(file));
741
+ } catch {
742
+ return null;
743
+ }
744
+ if (isLegacyToken(parsed)) {
745
+ writeVault(file, parsed, store);
746
+ return parsed;
747
+ }
748
+ if (!isEnvelope(parsed)) return null;
749
+ const keys = store ?? storeForWrap(parsed.wrap, file);
750
+ if (!keys) return null;
751
+ const key = keys.load();
752
+ if (!key) return null;
753
+ try {
754
+ return JSON.parse(decryptJson(parsed, key));
755
+ } catch (e) {
756
+ if (e instanceof TokenDecryptError) return null;
757
+ throw e;
758
+ }
759
+ }
760
+ function writeVault(file, value, store) {
761
+ const keys = store ?? storeForWrite(file);
762
+ let key = keys.load();
763
+ if (!key) {
764
+ key = crypto2.randomBytes(32);
765
+ keys.save(key);
766
+ }
767
+ const envelope = {
768
+ kty: KTY,
769
+ v: 1,
770
+ alg: "A256GCM",
771
+ wrap: keys.id,
772
+ ...encryptJson(JSON.stringify(value), key)
773
+ };
774
+ atomicWrite(file, `${JSON.stringify(envelope, null, 2)}
775
+ `);
776
+ }
777
+ function clearVault(file) {
778
+ const wrap = peekWrap(file);
779
+ let existed = import_fs4.default.existsSync(file);
780
+ import_fs4.default.rmSync(file, { force: true });
781
+ if (wrap) {
782
+ try {
783
+ keyStoreById(wrap, file).clear();
784
+ } catch {
785
+ }
786
+ }
787
+ const keyFile = tokenKeyPath(file);
788
+ if (import_fs4.default.existsSync(keyFile)) {
789
+ import_fs4.default.rmSync(keyFile, { force: true });
790
+ existed = true;
791
+ }
792
+ forgetKeyFile(keyFile);
793
+ return existed;
794
+ }
795
+ function storeForWrite(file) {
796
+ const wrap = peekWrap(file);
797
+ if (wrap) {
798
+ const existing = storeForWrap(wrap, file);
799
+ if (existing?.load()) return existing;
800
+ }
801
+ return createDefaultKeyStore(file);
802
+ }
803
+ function storeForWrap(wrap, file) {
804
+ try {
805
+ return keyStoreById(wrap, file);
806
+ } catch {
807
+ return null;
808
+ }
809
+ }
810
+ function peekWrap(file) {
811
+ if (!import_fs4.default.existsSync(file)) return null;
812
+ try {
813
+ const parsed = JSON.parse(readPrivateFile(file));
814
+ if (parsed?.kty === KTY && typeof parsed.wrap === "string") return parsed.wrap;
815
+ } catch {
816
+ return null;
817
+ }
818
+ return null;
819
+ }
820
+ function isLegacyToken(value) {
821
+ if (!value || typeof value !== "object") return false;
822
+ const rec = value;
823
+ return typeof rec.accessToken === "string" && rec.kty !== KTY;
824
+ }
825
+ function isEnvelope(value) {
826
+ if (!value || typeof value !== "object") return false;
827
+ const v = value;
828
+ 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";
829
+ }
830
+ function encryptJson(plain, key) {
831
+ const iv = crypto2.randomBytes(12);
832
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
833
+ const ct = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
834
+ return {
835
+ iv: iv.toString("base64"),
836
+ tag: cipher.getAuthTag().toString("base64"),
837
+ ct: ct.toString("base64")
838
+ };
839
+ }
840
+ function decryptJson(env, key) {
841
+ try {
842
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
843
+ decipher.setAuthTag(Buffer.from(env.tag, "base64"));
844
+ return Buffer.concat([
845
+ decipher.update(Buffer.from(env.ct, "base64")),
846
+ decipher.final()
847
+ ]).toString("utf8");
848
+ } catch {
849
+ throw new TokenDecryptError();
850
+ }
851
+ }
852
+ function atomicWrite(file, contents) {
853
+ const tmp = `${file}.${process.pid}.tmp`;
854
+ try {
855
+ writePrivateFile(tmp, contents);
856
+ try {
857
+ if (import_fs4.default.existsSync(file)) import_fs4.default.unlinkSync(file);
858
+ import_fs4.default.renameSync(tmp, file);
859
+ } catch {
860
+ writePrivateFile(file, contents);
861
+ import_fs4.default.rmSync(tmp, { force: true });
862
+ }
863
+ } catch (e) {
864
+ import_fs4.default.rmSync(tmp, { force: true });
865
+ throw e;
866
+ }
867
+ }
868
+
349
869
  // src/core/oauth-team.ts
350
- var import_axios2 = __toESM(require("axios"));
351
- var import_fs3 = __toESM(require("fs"));
352
- var import_path2 = __toESM(require("path"));
353
- var import_os = __toESM(require("os"));
354
- var TOKEN_FILE = import_path2.default.join(import_os.default.homedir(), ".connect-api-cli-token.json");
355
870
  var cachedTeamId;
356
871
  function readPersistedTeamId() {
357
872
  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;
873
+ const data = readVault(tokenFilePath());
874
+ return data?.teamId || void 0;
361
875
  } catch {
362
876
  return void 0;
363
877
  }
364
878
  }
365
879
  function writePersistedTeamId(teamId) {
366
880
  try {
367
- if (!import_fs3.default.existsSync(TOKEN_FILE)) return;
368
- const data = JSON.parse(readPrivateFile(TOKEN_FILE));
881
+ const data = readVault(tokenFilePath());
882
+ if (!data) return;
369
883
  data.teamId = teamId;
370
- writePrivateFile(TOKEN_FILE, JSON.stringify(data, null, 2));
884
+ writeVault(tokenFilePath(), data);
371
885
  } catch {
372
886
  }
373
887
  }
@@ -375,8 +889,8 @@ async function resolveOAuthTeamId(cfg, accessToken) {
375
889
  if (cfg.teamId) {
376
890
  return cfg.teamId;
377
891
  }
378
- if (cachedTeamId !== void 0) {
379
- return cachedTeamId || void 0;
892
+ if (cachedTeamId) {
893
+ return cachedTeamId;
380
894
  }
381
895
  const persisted = readPersistedTeamId();
382
896
  if (persisted) {
@@ -394,26 +908,18 @@ async function resolveOAuthTeamId(cfg, accessToken) {
394
908
  maxRedirects: 0
395
909
  }
396
910
  );
397
- const teams = res.data.teams || [];
398
911
  if (res.data.ret && res.data.ret.code !== 0) {
399
912
  throw new Error(
400
913
  `Failed to list teams for OAuth teamId: ${res.data.ret.msg || JSON.stringify(res.data.ret)}`
401
914
  );
402
915
  }
403
- if (teams.length === 0) {
404
- cachedTeamId = null;
916
+ const firstTeam = res.data.teams?.[0];
917
+ if (!firstTeam?.id) {
405
918
  throw new Error("OAuth account has no teams. Cannot set teamId for API calls.");
406
919
  }
407
- if (teams.length === 1) {
408
- cachedTeamId = teams[0].id;
409
- writePersistedTeamId(cachedTeamId);
410
- return cachedTeamId;
411
- }
412
- cachedTeamId = null;
413
- const preview = teams.slice(0, 8).map((t) => `${t.id}${t.name ? `(${t.name})` : ""}`).join(", ");
414
- throw new Error(
415
- `Multiple teams found (${teams.length}). Set AGC_TEAM_ID to one of: ${preview}`
416
- );
920
+ cachedTeamId = firstTeam.id;
921
+ writePersistedTeamId(cachedTeamId);
922
+ return cachedTeamId;
417
923
  }
418
924
  function clearOAuthTeamIdCache() {
419
925
  cachedTeamId = void 0;
@@ -421,9 +927,9 @@ function clearOAuthTeamIdCache() {
421
927
 
422
928
  // src/core/deveco-token.ts
423
929
  var import_crypto = require("crypto");
424
- var import_fs4 = require("fs");
425
- var import_os2 = require("os");
426
- var import_path3 = require("path");
930
+ var import_fs5 = require("fs");
931
+ var import_os3 = require("os");
932
+ var import_path4 = require("path");
427
933
  var ALGORITHM = "aes-256-gcm";
428
934
  var KEY_LENGTH = 32;
429
935
  var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
@@ -437,11 +943,11 @@ function decryptAesGcm(ciphertext, key, iv, authTag) {
437
943
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
438
944
  }
439
945
  function readJson(filePath) {
440
- return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
946
+ return JSON.parse((0, import_fs5.readFileSync)(filePath, "utf8"));
441
947
  }
442
948
  function requireFile(filePath, label) {
443
949
  try {
444
- return (0, import_fs4.readFileSync)(filePath);
950
+ return (0, import_fs5.readFileSync)(filePath);
445
951
  } catch (err) {
446
952
  const code = err.code;
447
953
  if (code === "ENOENT") {
@@ -457,8 +963,8 @@ function loadKek(kekId, keysDir) {
457
963
  if (!KEK_VERSIONS.includes(kekId)) {
458
964
  throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
459
965
  }
460
- const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
461
- const keysDirBase = (0, import_path3.resolve)(keysDir);
966
+ const rootKeyPath = (0, import_path4.resolve)((0, import_path4.join)(keysDir, `${kekId}.bin`));
967
+ const keysDirBase = (0, import_path4.resolve)(keysDir);
462
968
  if (!rootKeyPath.startsWith(keysDirBase)) {
463
969
  throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
464
970
  }
@@ -469,16 +975,16 @@ function loadKek(kekId, keysDir) {
469
975
  return kek;
470
976
  }
471
977
  function decryptToken(tokenDir, keysDir) {
472
- const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
978
+ const blob = readJson((0, import_path4.join)(tokenDir, "token.enc"));
473
979
  if (blob.algorithm !== ALGORITHM) {
474
980
  throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
475
981
  }
476
982
  if (!blob.ciphertext || !blob.iv || !blob.authTag) {
477
- throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.enc")}`);
983
+ throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.enc")}`);
478
984
  }
479
- const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
985
+ const wrapped = readJson((0, import_path4.join)(tokenDir, "token.dek"));
480
986
  if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
481
- throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.dek")}`);
987
+ throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path4.join)(tokenDir, "token.dek")}`);
482
988
  }
483
989
  const kek = loadKek(wrapped.kekId, keysDir);
484
990
  const dek = decryptAesGcm(
@@ -520,10 +1026,10 @@ function extractJwt(plaintext) {
520
1026
  return { jwt };
521
1027
  }
522
1028
  function configHome() {
523
- return process.env.XDG_CONFIG_HOME || (0, import_path3.join)((0, import_os2.homedir)(), ".config");
1029
+ return process.env.XDG_CONFIG_HOME || (0, import_path4.join)((0, import_os3.homedir)(), ".config");
524
1030
  }
525
1031
  function candidatesFor(source) {
526
- const home = (0, import_os2.homedir)();
1032
+ const home = (0, import_os3.homedir)();
527
1033
  if (CLI_SOURCE_ALIASES.includes(source)) {
528
1034
  if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
529
1035
  return candidatesFor("deveco-code").map((c) => ({
@@ -535,8 +1041,8 @@ function candidatesFor(source) {
535
1041
  return [
536
1042
  {
537
1043
  source,
538
- tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
539
- keysDir: (0, import_path3.join)(home, ".local", "share", "deveco-cli", "keys"),
1044
+ tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path4.join)(home, ".config", "deveco-cli"),
1045
+ keysDir: (0, import_path4.join)(home, ".local", "share", "deveco-cli", "keys"),
540
1046
  via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
541
1047
  }
542
1048
  ];
@@ -544,31 +1050,31 @@ function candidatesFor(source) {
544
1050
  const appName = SOURCE_APP_NAMES[source];
545
1051
  const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
546
1052
  if (source === "deveco-code" && viaEnv) {
547
- const tokenDir = (0, import_path3.resolve)(viaEnv);
548
- return [{ source, tokenDir, keysDir: (0, import_path3.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
1053
+ const tokenDir = (0, import_path4.resolve)(viaEnv);
1054
+ return [{ source, tokenDir, keysDir: (0, import_path4.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
549
1055
  }
550
1056
  let dirs;
551
1057
  if (process.platform === "win32") {
552
- const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
553
- dirs = [(0, import_path3.join)(appData, appName), (0, import_path3.join)(home, ".config", appName)];
1058
+ const appData = process.env.APPDATA || (0, import_path4.join)(home, "AppData", "Roaming");
1059
+ dirs = [(0, import_path4.join)(appData, appName), (0, import_path4.join)(home, ".config", appName)];
554
1060
  } else if (process.platform === "darwin") {
555
1061
  dirs = [
556
- (0, import_path3.join)(configHome(), appName),
557
- (0, import_path3.join)(home, "Library", "Application Support", appName)
1062
+ (0, import_path4.join)(configHome(), appName),
1063
+ (0, import_path4.join)(home, "Library", "Application Support", appName)
558
1064
  ];
559
1065
  } else {
560
- dirs = [(0, import_path3.join)(configHome(), appName)];
1066
+ dirs = [(0, import_path4.join)(configHome(), appName)];
561
1067
  }
562
1068
  return dirs.map((tokenDir) => ({
563
1069
  source,
564
1070
  tokenDir,
565
- keysDir: (0, import_path3.join)(tokenDir, "keys"),
1071
+ keysDir: (0, import_path4.join)(tokenDir, "keys"),
566
1072
  via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
567
1073
  }));
568
1074
  }
569
1075
  function resolveLocation(source) {
570
1076
  const candidates = candidatesFor(source);
571
- const hit = candidates.find((c) => (0, import_fs4.existsSync)((0, import_path3.join)(c.tokenDir, "token.enc")));
1077
+ const hit = candidates.find((c) => (0, import_fs5.existsSync)((0, import_path4.join)(c.tokenDir, "token.enc")));
572
1078
  if (hit) {
573
1079
  return hit;
574
1080
  }
@@ -579,59 +1085,220 @@ ${tried}`
579
1085
  );
580
1086
  }
581
1087
  function loadDevecoLocalToken(source, authDir) {
582
- const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path3.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
1088
+ const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path4.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
583
1089
  const plaintext = decryptToken(location.tokenDir, location.keysDir);
584
1090
  const { jwt, expMs } = extractJwt(plaintext);
585
1091
  return { jwt, expMs, location };
586
1092
  }
587
1093
 
1094
+ // src/core/login-page.ts
1095
+ 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>`;
1096
+ 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>`;
1097
+ var PAGES = {
1098
+ success: {
1099
+ icon: SUCCESS_ICON,
1100
+ title: "\u767B\u5F55\u6210\u529F",
1101
+ message: "\u6388\u6743\u5DF2\u5B8C\u6210\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3\u5E76\u56DE\u5230\u7EC8\u7AEF",
1102
+ bgGradient: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
1103
+ },
1104
+ failed: {
1105
+ icon: FAILED_ICON,
1106
+ title: "\u767B\u5F55\u5931\u8D25",
1107
+ message: "\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5",
1108
+ bgGradient: "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)"
1109
+ }
1110
+ };
1111
+ var TEMPLATE = `<!DOCTYPE html>
1112
+ <html lang="zh-CN">
1113
+ <head>
1114
+ <meta charset="utf-8">
1115
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1116
+ <title>{{TITLE}}</title>
1117
+ <style>
1118
+ * { box-sizing: border-box; }
1119
+ body {
1120
+ margin: 0;
1121
+ min-height: 100vh;
1122
+ display: flex;
1123
+ align-items: center;
1124
+ justify-content: center;
1125
+ background: {{BG_GRADIENT}};
1126
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Roboto, sans-serif;
1127
+ -webkit-font-smoothing: antialiased;
1128
+ }
1129
+ .card {
1130
+ background: transparent;
1131
+ border-radius: 20px;
1132
+ padding: 48px 56px;
1133
+ text-align: center;
1134
+ max-width: 480px;
1135
+ }
1136
+ .icon {
1137
+ display: flex;
1138
+ justify-content: center;
1139
+ margin-bottom: 20px;
1140
+ animation: bounceIn 0.6s ease-out;
1141
+ }
1142
+ .icon svg { display: block; }
1143
+ h1 {
1144
+ margin: 0 0 12px;
1145
+ font-size: 26px;
1146
+ font-weight: 600;
1147
+ color: #fff;
1148
+ letter-spacing: 0.02em;
1149
+ }
1150
+ p {
1151
+ margin: 0;
1152
+ font-size: 15px;
1153
+ line-height: 1.6;
1154
+ color: rgba(255, 255, 255, 0.88);
1155
+ }
1156
+ @keyframes bounceIn {
1157
+ 0% { transform: scale(0); opacity: 0; }
1158
+ 50% { transform: scale(1.15); }
1159
+ 100% { transform: scale(1); opacity: 1; }
1160
+ }
1161
+ </style>
1162
+ </head>
1163
+ <body>
1164
+ <div class="card">
1165
+ <div class="icon">{{ICON}}</div>
1166
+ <h1>{{TITLE}}</h1>
1167
+ <p>{{MESSAGE}}</p>
1168
+ </div>
1169
+ </body>
1170
+ </html>`;
1171
+ function escapeHtml(value) {
1172
+ return value.replace(/[&<>"']/g, (ch) => {
1173
+ switch (ch) {
1174
+ case "&":
1175
+ return "&amp;";
1176
+ case "<":
1177
+ return "&lt;";
1178
+ case ">":
1179
+ return "&gt;";
1180
+ case '"':
1181
+ return "&quot;";
1182
+ case "'":
1183
+ return "&#39;";
1184
+ default:
1185
+ return ch;
1186
+ }
1187
+ });
1188
+ }
1189
+ function renderLoginPage(kind, options) {
1190
+ const vars = PAGES[kind];
1191
+ const message = options?.message?.trim() ? options.message : vars.message;
1192
+ return TEMPLATE.replace(/\{\{ICON\}\}/g, vars.icon).replace(/\{\{TITLE\}\}/g, escapeHtml(vars.title)).replace(/\{\{MESSAGE\}\}/g, escapeHtml(message)).replace(/\{\{BG_GRADIENT\}\}/g, vars.bgGradient);
1193
+ }
1194
+
588
1195
  // src/core/auth-mgr.ts
589
- var crypto2 = __toESM(require("crypto"));
1196
+ var crypto3 = __toESM(require("crypto"));
590
1197
  var http = __toESM(require("http"));
591
- var import_child_process = require("child_process");
592
- var import_fs5 = __toESM(require("fs"));
593
- var import_path4 = __toESM(require("path"));
594
- var import_os3 = __toESM(require("os"));
1198
+ var import_child_process2 = require("child_process");
1199
+ var import_fs6 = __toESM(require("fs"));
595
1200
  var DEVECO_CACHE_TTL_MS = 30 * 60 * 1e3;
1201
+ var OAUTH_EXPIRY_SKEW_MS = 5 * 60 * 1e3;
1202
+ function oauthAccessDecision(cache, now = Date.now(), skewMs = OAUTH_EXPIRY_SKEW_MS) {
1203
+ if (!cache?.accessToken) return "relogin";
1204
+ const expiresAt = cache.expiresAt;
1205
+ const hasExpiry = typeof expiresAt === "number" && Number.isFinite(expiresAt) && expiresAt > 0;
1206
+ if (!hasExpiry) return "use";
1207
+ if (expiresAt > now + skewMs) return "use";
1208
+ if (cache.refreshToken) return "refresh";
1209
+ return "relogin";
1210
+ }
1211
+ function resolveExpiresAt(expireTime, previousExpiresAt, now = Date.now()) {
1212
+ if (Number.isFinite(expireTime) && expireTime > 0) return now + expireTime * 1e3;
1213
+ if (typeof previousExpiresAt === "number" && Number.isFinite(previousExpiresAt) && previousExpiresAt > now + OAUTH_EXPIRY_SKEW_MS) {
1214
+ return previousExpiresAt;
1215
+ }
1216
+ return 0;
1217
+ }
1218
+ var NOT_LOGGED_IN = "Not logged in. Run `connect-api-cli auth login` and finish authorization in the browser.";
1219
+ var NEED_RELOGIN = "OAuth token refresh failed, need to re-login";
1220
+ var HARMONY_AA_CANDIDATES = ["/bin/aa", "/system/bin/aa", "/usr/bin/aa"];
1221
+ function detectBrowserHost(input) {
1222
+ const platform = input?.platform ?? process.platform;
1223
+ if (platform === "win32") return "win32";
1224
+ if (platform === "darwin") return "darwin";
1225
+ const osRelease = input?.osRelease ?? readOsRelease();
1226
+ const hasAa = input?.hasAa ?? harmonyAaExists();
1227
+ if (/harmonyos|openharmony/i.test(osRelease) || hasAa) return "harmony";
1228
+ return "linux";
1229
+ }
1230
+ function browserLaunchSpec(url, host = detectBrowserHost()) {
1231
+ if (host === "win32") {
1232
+ return { file: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
1233
+ }
1234
+ if (host === "darwin") {
1235
+ return { file: "open", args: [url] };
1236
+ }
1237
+ if (host === "harmony") {
1238
+ return { file: "aa", args: ["start", "-A", "ohos.want.action.viewData", "-U", url] };
1239
+ }
1240
+ return { file: "xdg-open", args: [url] };
1241
+ }
596
1242
  var AuthManager = class {
597
- static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
1243
+ /** 并发的 OAuth 登录共用同一次浏览器授权。 */
598
1244
  static pendingOAuthLogin;
1245
+ /** 并发请求共用一次刷新,避免同时打刷新接口或互相清缓存。 */
1246
+ static oauthRefreshInFlight = null;
599
1247
  /**
600
1248
  * 获取当前生效的 access token,并具备自动刷新能力:
601
- * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
1249
+ * - OAuth:未过期,或没有过期时间时,直接用缓存。过期且有 refreshToken 才刷新。
1250
+ * 请求路径不打开浏览器;需要重新授权时抛错,由 `auth login` 或 DevEco 降级处理。
602
1251
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
603
1252
  * - deveco:过期后重新解密本地登录态并 refresh 换取
604
1253
  *
605
- * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
1254
+ * force 跳过缓存(供 401 重试使用)。OAuth 在 force 时只走 refreshToken。
606
1255
  */
607
1256
  static async getAccessToken(force = false) {
608
1257
  const { config: config2, cache } = this.getStatus();
609
- return this.getToken(config2, cache, force);
610
- }
611
- static async getToken(cfg, cache, force = false) {
612
- if (!force && cache && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
1258
+ if (config2.authMode === "oauth") {
1259
+ return this.getOAuthAccessToken(config2, cache, force, false);
1260
+ }
1261
+ if (!force && cache && cache.expiresAt > Date.now() + OAUTH_EXPIRY_SKEW_MS) {
613
1262
  return cache.accessToken;
614
1263
  }
615
- if (cfg.authMode === "oauth" && cache?.refreshToken) {
1264
+ return this.acquire(config2);
1265
+ }
1266
+ /**
1267
+ * interactive 为真时,缓存不可用会打开浏览器。
1268
+ * 请求路径(interactive 为假)只使用或刷新已有 token,不会占用 12306。
1269
+ */
1270
+ static async getOAuthAccessToken(cfg, cache, force, interactive) {
1271
+ if (!force) {
1272
+ const decision = oauthAccessDecision(cache);
1273
+ if (decision === "use") return cache.accessToken;
1274
+ if (decision === "refresh") {
1275
+ try {
1276
+ return await this.refreshCachedOAuth(cfg, cache);
1277
+ } catch (e) {
1278
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache?.accessToken) {
1279
+ return cache.accessToken;
1280
+ }
1281
+ if (!interactive) throw e;
1282
+ }
1283
+ } else if (!interactive) {
1284
+ throw new Error(NOT_LOGGED_IN);
1285
+ }
1286
+ } else if (cache?.refreshToken) {
616
1287
  try {
617
- const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
618
- const expiresAt = Date.now() + refreshed.expireTime * 1e3;
619
- this.writeCache({
620
- accessToken: refreshed.accessToken,
621
- expiresAt,
622
- clientId: cfg.clientId,
623
- domain: cfg.domain,
624
- authMode: cfg.authMode,
625
- refreshToken: cache.refreshToken
626
- // 刷新接口不返回新 refreshToken,沿用旧值
627
- });
628
- return refreshed.accessToken;
1288
+ return await this.refreshCachedOAuth(cfg, cache);
629
1289
  } catch (e) {
630
- console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
631
- this.clearCache();
1290
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache.accessToken && !interactive) {
1291
+ return cache.accessToken;
1292
+ }
1293
+ if (!interactive) throw e;
632
1294
  }
1295
+ } else if (!interactive) {
1296
+ throw new Error(NOT_LOGGED_IN);
633
1297
  }
634
- return this.acquire(cfg);
1298
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
1299
+ this.pendingOAuthLogin = void 0;
1300
+ });
1301
+ return this.pendingOAuthLogin;
635
1302
  }
636
1303
  /** 登录入口:按当前认证模式获取并缓存 token */
637
1304
  static async login() {
@@ -641,10 +1308,8 @@ var AuthManager = class {
641
1308
  /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
642
1309
  static async acquire(cfg) {
643
1310
  if (cfg.authMode === "oauth") {
644
- this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
645
- this.pendingOAuthLogin = void 0;
646
- });
647
- return this.pendingOAuthLogin;
1311
+ const cache = this.matchingCache(cfg, this.readCache());
1312
+ return this.getOAuthAccessToken(cfg, cache, false, true);
648
1313
  }
649
1314
  if (cfg.authMode === "deveco") {
650
1315
  try {
@@ -654,7 +1319,7 @@ var AuthManager = class {
654
1319
  const oauthConfig = getConfig("oauth");
655
1320
  const cache = this.matchingCache(oauthConfig, this.readCache());
656
1321
  console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
657
- return this.getToken(oauthConfig, cache);
1322
+ return this.getOAuthAccessToken(oauthConfig, cache, false, true);
658
1323
  }
659
1324
  }
660
1325
  if (cfg.authMode === "service_account") {
@@ -685,51 +1350,68 @@ var AuthManager = class {
685
1350
  }
686
1351
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
687
1352
  }
688
- /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
1353
+ /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器。同一进程只开一次。 */
689
1354
  static loginOAuth(cfg) {
690
1355
  return new Promise((resolve2, reject) => {
691
1356
  const redirectUri = cfg.oauth.redirectUri;
692
1357
  const port = Number(new URL(redirectUri).port || 80);
693
- const state = crypto2.randomBytes(32).toString("hex");
694
- const server = http.createServer(async (req, res) => {
1358
+ const state = crypto3.randomBytes(32).toString("hex");
1359
+ let settled = false;
1360
+ let server;
1361
+ const finish = (err, token) => {
1362
+ if (settled) return;
1363
+ settled = true;
1364
+ server.close();
1365
+ if (err) reject(err);
1366
+ else resolve2(token);
1367
+ };
1368
+ server = http.createServer(async (req, res) => {
695
1369
  try {
696
- const url = new URL(req.url, `http://${req.headers.host}`);
1370
+ const url = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
697
1371
  const code = url.searchParams.get("code");
698
1372
  const returnedState = url.searchParams.get("state");
699
- if (!code || returnedState !== state) {
700
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
701
- res.end("<h3>\u65E0\u6548\u7684\u56DE\u8C03\u53C2\u6570</h3>");
1373
+ const oauthError = url.searchParams.get("error");
1374
+ if (!code && !oauthError) {
1375
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
1376
+ res.end();
1377
+ return;
1378
+ }
1379
+ if (oauthError || !code || returnedState !== state) {
1380
+ 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";
1381
+ sendLoginPage(res, "failed", detail, 400);
1382
+ finish(new Error(detail));
702
1383
  return;
703
1384
  }
704
1385
  const token = await AuthService.getOAuthToken(code, redirectUri);
705
- const expiresAt = Date.now() + token.expireTime * 1e3;
706
1386
  clearOAuthTeamIdCache();
707
1387
  this.writeCache({
708
1388
  accessToken: token.accessToken,
709
- expiresAt,
1389
+ expiresAt: resolveExpiresAt(token.expireTime),
710
1390
  clientId: cfg.clientId,
711
1391
  domain: cfg.domain,
712
1392
  authMode: cfg.authMode,
713
1393
  refreshToken: token.refreshToken
714
1394
  });
715
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
716
- 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>');
717
- server.close();
718
- resolve2(token.accessToken);
1395
+ sendLoginPage(res, "success");
1396
+ finish(void 0, token.accessToken);
719
1397
  } catch (err) {
720
- server.close();
721
- reject(err instanceof Error ? err : new Error(String(err)));
1398
+ const message = err instanceof Error ? err.message : String(err);
1399
+ if (!res.headersSent) sendLoginPage(res, "failed", message || "\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5");
1400
+ finish(err instanceof Error ? err : new Error(message));
722
1401
  }
723
1402
  });
724
1403
  server.on("error", (err) => {
725
- server.close();
726
- reject(err);
1404
+ if (err.code === "EADDRINUSE") {
1405
+ 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"));
1406
+ return;
1407
+ }
1408
+ finish(err);
727
1409
  });
728
1410
  server.listen(port, () => {
729
1411
  const authUrl = AuthService.buildAuthUrl(state);
730
1412
  console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
731
1413
  console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
732
- openBrowser(authUrl);
1414
+ launchBrowser(authUrl);
733
1415
  });
734
1416
  });
735
1417
  }
@@ -766,50 +1448,92 @@ var AuthManager = class {
766
1448
  static matchingCache(cfg, cache) {
767
1449
  return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
768
1450
  }
769
- static readCache() {
1451
+ static refreshCachedOAuth(cfg, cache) {
1452
+ if (!this.oauthRefreshInFlight) {
1453
+ this.oauthRefreshInFlight = this.doRefreshCachedOAuth(cfg, cache).finally(() => {
1454
+ this.oauthRefreshInFlight = null;
1455
+ });
1456
+ }
1457
+ return this.oauthRefreshInFlight;
1458
+ }
1459
+ static async doRefreshCachedOAuth(cfg, cache) {
770
1460
  try {
771
- if (import_fs5.default.existsSync(this.cacheFile)) {
772
- const data = readPrivateFile(this.cacheFile);
773
- return JSON.parse(data);
774
- }
1461
+ const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
1462
+ const refreshToken = refreshed.refreshToken || cache.refreshToken;
1463
+ this.writeCache({
1464
+ accessToken: refreshed.accessToken,
1465
+ expiresAt: resolveExpiresAt(refreshed.expireTime, cache.expiresAt),
1466
+ clientId: cfg.clientId,
1467
+ domain: cfg.domain,
1468
+ authMode: cfg.authMode,
1469
+ refreshToken
1470
+ });
1471
+ return refreshed.accessToken;
775
1472
  } catch (e) {
1473
+ if (isDefinitiveOAuthRefreshFailure(e)) {
1474
+ console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
1475
+ this.clearCache();
1476
+ throw new Error(NEED_RELOGIN);
1477
+ }
1478
+ console.error("OAuth token refresh failed:", e instanceof Error ? e.message : String(e));
1479
+ throw e;
776
1480
  }
777
- return null;
1481
+ }
1482
+ static readCache() {
1483
+ const data = readVault(tokenFilePath());
1484
+ if (!data || typeof data !== "object") return null;
1485
+ const cache = data;
1486
+ return typeof cache.accessToken === "string" ? cache : null;
778
1487
  }
779
1488
  static writeCache(cache) {
780
- try {
781
- writePrivateFile(this.cacheFile, JSON.stringify(cache, null, 2));
782
- } catch (e) {
1489
+ const prev = this.readCache();
1490
+ const sameIdentity = !!prev && prev.clientId === cache.clientId && prev.domain === cache.domain && prev.authMode === cache.authMode;
1491
+ const next = { ...sameIdentity ? prev : {}, ...cache };
1492
+ if (cache.teamId === void 0 && sameIdentity && prev?.teamId) next.teamId = prev.teamId;
1493
+ if (Object.prototype.hasOwnProperty.call(cache, "refreshToken") && !cache.refreshToken) {
1494
+ delete next.refreshToken;
783
1495
  }
1496
+ writeVault(tokenFilePath(), next);
784
1497
  }
785
1498
  /**
786
1499
  * 清除缓存的 Token(登出)
787
1500
  */
788
1501
  static clearCache() {
789
1502
  clearOAuthTeamIdCache();
790
- try {
791
- if (import_fs5.default.existsSync(this.cacheFile)) {
792
- import_fs5.default.unlinkSync(this.cacheFile);
793
- return true;
794
- }
795
- return false;
796
- } catch (e) {
797
- return false;
798
- }
1503
+ return clearVault(tokenFilePath());
799
1504
  }
800
1505
  };
801
- function openBrowser(url) {
802
- const platform = process.platform;
803
- const cmd = platform === "darwin" ? "open" : platform === "win32" ? 'start ""' : "xdg-open";
804
- (0, import_child_process.exec)(`${cmd} "${url}"`, (err) => {
1506
+ function sendLoginPage(res, kind, message, status = 200) {
1507
+ const html = renderLoginPage(kind, message ? { message } : void 0);
1508
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
1509
+ res.end(html);
1510
+ }
1511
+ function launchBrowser(url) {
1512
+ const host = detectBrowserHost();
1513
+ const spec = browserLaunchSpec(url, host);
1514
+ if (host === "harmony") spec.file = resolveHarmonyAa();
1515
+ (0, import_child_process2.execFile)(spec.file, spec.args, { windowsHide: true }, (err) => {
805
1516
  if (err) {
806
1517
  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");
807
1518
  }
808
1519
  });
809
1520
  }
1521
+ function readOsRelease() {
1522
+ try {
1523
+ if (import_fs6.default.existsSync("/etc/os-release")) return import_fs6.default.readFileSync("/etc/os-release", "utf8");
1524
+ } catch {
1525
+ }
1526
+ return "";
1527
+ }
1528
+ function harmonyAaExists() {
1529
+ return HARMONY_AA_CANDIDATES.some((file) => import_fs6.default.existsSync(file));
1530
+ }
1531
+ function resolveHarmonyAa() {
1532
+ return HARMONY_AA_CANDIDATES.find((file) => import_fs6.default.existsSync(file)) ?? "aa";
1533
+ }
810
1534
 
811
1535
  // src/core/request-source.ts
812
- var import_fs6 = __toESM(require("fs"));
1536
+ var import_fs7 = __toESM(require("fs"));
813
1537
  var import_path5 = __toESM(require("path"));
814
1538
  var REQUEST_SOURCE_HEADER = "Request-Source";
815
1539
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
@@ -950,7 +1674,7 @@ function getRequestSource() {
950
1674
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
951
1675
  }
952
1676
  function readVersion() {
953
- const fromBuild = injected(true ? "1.1.9" : void 0);
1677
+ const fromBuild = injected(true ? "1.1.11" : void 0);
954
1678
  if (fromBuild) return fromBuild;
955
1679
  const candidates = [
956
1680
  import_path5.default.join(__dirname, "..", "..", "package.json"),
@@ -958,7 +1682,7 @@ function readVersion() {
958
1682
  ];
959
1683
  for (const pkgPath of candidates) {
960
1684
  try {
961
- const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
1685
+ const pkg = JSON.parse(import_fs7.default.readFileSync(pkgPath, "utf8"));
962
1686
  if (pkg.version) return pkg.version;
963
1687
  } catch {
964
1688
  }
@@ -1052,7 +1776,7 @@ connectApiClient.interceptors.response.use(
1052
1776
  original._retry = true;
1053
1777
  try {
1054
1778
  const cfg = getConfig();
1055
- const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
1779
+ const newToken = await AuthManager.getAccessToken(true);
1056
1780
  if (!original.headers) {
1057
1781
  original.headers = {};
1058
1782
  }
@@ -1060,6 +1784,10 @@ connectApiClient.interceptors.response.use(
1060
1784
  if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1061
1785
  return connectApiClient(original);
1062
1786
  } catch (e) {
1787
+ if (e instanceof Error && e.message) {
1788
+ err.message = `${err.message}
1789
+ ${e.message}`;
1790
+ }
1063
1791
  return Promise.reject(err);
1064
1792
  }
1065
1793
  }
@@ -1413,7 +2141,7 @@ var ProjectService = class {
1413
2141
 
1414
2142
  // src/services/upload.ts
1415
2143
  var import_axios4 = __toESM(require("axios"));
1416
- var import_fs7 = __toESM(require("fs"));
2144
+ var import_fs8 = __toESM(require("fs"));
1417
2145
  var import_path6 = __toESM(require("path"));
1418
2146
  function pickObjectId(res) {
1419
2147
  return res.urlInfo?.objectId || res.objectId;
@@ -1453,7 +2181,7 @@ var UploadService = class {
1453
2181
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1454
2182
  */
1455
2183
  static async uploadFile(options) {
1456
- const stat = import_fs7.default.statSync(options.filePath);
2184
+ const stat = import_fs8.default.statSync(options.filePath);
1457
2185
  const fileName = import_path6.default.basename(options.filePath) || "unknown";
1458
2186
  if (stat.size < 5 * 1024 * 1024) {
1459
2187
  return this.uploadSingleFile(options, fileName, stat.size);
@@ -1495,7 +2223,7 @@ var UploadService = class {
1495
2223
  );
1496
2224
  }
1497
2225
  const { url, headers } = urlRes.urlInfo;
1498
- const fileStream = import_fs7.default.createReadStream(options.filePath);
2226
+ const fileStream = import_fs8.default.createReadStream(options.filePath);
1499
2227
  await import_axios4.default.put(url, fileStream, {
1500
2228
  headers: this.buildObsPutHeaders(headers, contentLength),
1501
2229
  maxBodyLength: Infinity,
@@ -1536,7 +2264,7 @@ var UploadService = class {
1536
2264
  if (!uploadInfoMap) {
1537
2265
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1538
2266
  }
1539
- const fd = import_fs7.default.openSync(options.filePath, "r");
2267
+ const fd = import_fs8.default.openSync(options.filePath, "r");
1540
2268
  const composeReqBody = {};
1541
2269
  for (let i = 1; i <= partsCount; i++) {
1542
2270
  const propKey = `additionalProp${i}`;
@@ -1545,7 +2273,7 @@ var UploadService = class {
1545
2273
  const end = Math.min(start + partSize, fileSize);
1546
2274
  const length = end - start;
1547
2275
  const buffer = Buffer.alloc(length);
1548
- import_fs7.default.readSync(fd, buffer, 0, length, start);
2276
+ import_fs8.default.readSync(fd, buffer, 0, length, start);
1549
2277
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1550
2278
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1551
2279
  maxBodyLength: Infinity,
@@ -1557,7 +2285,7 @@ var UploadService = class {
1557
2285
  etag
1558
2286
  };
1559
2287
  }
1560
- import_fs7.default.closeSync(fd);
2288
+ import_fs8.default.closeSync(fd);
1561
2289
  await this.composeMultipart({
1562
2290
  objectId,
1563
2291
  nspUploadId,
@@ -1688,10 +2416,13 @@ var ProvisionService = class {
1688
2416
  // Annotate the CommonJS export names for ESM import in node:
1689
2417
  0 && (module.exports = {
1690
2418
  AuthService,
2419
+ OAuthRefreshRejectedError,
1691
2420
  ProjectService,
1692
2421
  ProvisionService,
1693
2422
  PublishService,
1694
2423
  UploadService,
1695
2424
  connectApiClient,
1696
- getConfig
2425
+ getConfig,
2426
+ isDefinitiveOAuthRefreshFailure,
2427
+ normalizeOAuthToken
1697
2428
  });