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/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
  }
@@ -413,9 +927,9 @@ function clearOAuthTeamIdCache() {
413
927
 
414
928
  // src/core/deveco-token.ts
415
929
  var import_crypto = require("crypto");
416
- var import_fs4 = require("fs");
417
- var import_os2 = require("os");
418
- var import_path3 = require("path");
930
+ var import_fs5 = require("fs");
931
+ var import_os3 = require("os");
932
+ var import_path4 = require("path");
419
933
  var ALGORITHM = "aes-256-gcm";
420
934
  var KEY_LENGTH = 32;
421
935
  var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
@@ -429,11 +943,11 @@ function decryptAesGcm(ciphertext, key, iv, authTag) {
429
943
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
430
944
  }
431
945
  function readJson(filePath) {
432
- return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
946
+ return JSON.parse((0, import_fs5.readFileSync)(filePath, "utf8"));
433
947
  }
434
948
  function requireFile(filePath, label) {
435
949
  try {
436
- return (0, import_fs4.readFileSync)(filePath);
950
+ return (0, import_fs5.readFileSync)(filePath);
437
951
  } catch (err) {
438
952
  const code = err.code;
439
953
  if (code === "ENOENT") {
@@ -449,8 +963,8 @@ function loadKek(kekId, keysDir) {
449
963
  if (!KEK_VERSIONS.includes(kekId)) {
450
964
  throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
451
965
  }
452
- const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
453
- 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);
454
968
  if (!rootKeyPath.startsWith(keysDirBase)) {
455
969
  throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
456
970
  }
@@ -461,16 +975,16 @@ function loadKek(kekId, keysDir) {
461
975
  return kek;
462
976
  }
463
977
  function decryptToken(tokenDir, keysDir) {
464
- const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
978
+ const blob = readJson((0, import_path4.join)(tokenDir, "token.enc"));
465
979
  if (blob.algorithm !== ALGORITHM) {
466
980
  throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
467
981
  }
468
982
  if (!blob.ciphertext || !blob.iv || !blob.authTag) {
469
- 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")}`);
470
984
  }
471
- const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
985
+ const wrapped = readJson((0, import_path4.join)(tokenDir, "token.dek"));
472
986
  if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
473
- 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")}`);
474
988
  }
475
989
  const kek = loadKek(wrapped.kekId, keysDir);
476
990
  const dek = decryptAesGcm(
@@ -512,10 +1026,10 @@ function extractJwt(plaintext) {
512
1026
  return { jwt };
513
1027
  }
514
1028
  function configHome() {
515
- 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");
516
1030
  }
517
1031
  function candidatesFor(source) {
518
- const home = (0, import_os2.homedir)();
1032
+ const home = (0, import_os3.homedir)();
519
1033
  if (CLI_SOURCE_ALIASES.includes(source)) {
520
1034
  if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
521
1035
  return candidatesFor("deveco-code").map((c) => ({
@@ -527,8 +1041,8 @@ function candidatesFor(source) {
527
1041
  return [
528
1042
  {
529
1043
  source,
530
- tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
531
- 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"),
532
1046
  via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
533
1047
  }
534
1048
  ];
@@ -536,31 +1050,31 @@ function candidatesFor(source) {
536
1050
  const appName = SOURCE_APP_NAMES[source];
537
1051
  const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
538
1052
  if (source === "deveco-code" && viaEnv) {
539
- const tokenDir = (0, import_path3.resolve)(viaEnv);
540
- 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" }];
541
1055
  }
542
1056
  let dirs;
543
1057
  if (process.platform === "win32") {
544
- const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
545
- 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)];
546
1060
  } else if (process.platform === "darwin") {
547
1061
  dirs = [
548
- (0, import_path3.join)(configHome(), appName),
549
- (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)
550
1064
  ];
551
1065
  } else {
552
- dirs = [(0, import_path3.join)(configHome(), appName)];
1066
+ dirs = [(0, import_path4.join)(configHome(), appName)];
553
1067
  }
554
1068
  return dirs.map((tokenDir) => ({
555
1069
  source,
556
1070
  tokenDir,
557
- keysDir: (0, import_path3.join)(tokenDir, "keys"),
1071
+ keysDir: (0, import_path4.join)(tokenDir, "keys"),
558
1072
  via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
559
1073
  }));
560
1074
  }
561
1075
  function resolveLocation(source) {
562
1076
  const candidates = candidatesFor(source);
563
- 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")));
564
1078
  if (hit) {
565
1079
  return hit;
566
1080
  }
@@ -571,59 +1085,220 @@ ${tried}`
571
1085
  );
572
1086
  }
573
1087
  function loadDevecoLocalToken(source, authDir) {
574
- 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);
575
1089
  const plaintext = decryptToken(location.tokenDir, location.keysDir);
576
1090
  const { jwt, expMs } = extractJwt(plaintext);
577
1091
  return { jwt, expMs, location };
578
1092
  }
579
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
+
580
1195
  // src/core/auth-mgr.ts
581
- var crypto2 = __toESM(require("crypto"));
1196
+ var crypto3 = __toESM(require("crypto"));
582
1197
  var http = __toESM(require("http"));
583
- var import_child_process = require("child_process");
584
- var import_fs5 = __toESM(require("fs"));
585
- var import_path4 = __toESM(require("path"));
586
- var import_os3 = __toESM(require("os"));
1198
+ var import_child_process2 = require("child_process");
1199
+ var import_fs6 = __toESM(require("fs"));
587
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
+ }
588
1242
  var AuthManager = class {
589
- static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
1243
+ /** 并发的 OAuth 登录共用同一次浏览器授权。 */
590
1244
  static pendingOAuthLogin;
1245
+ /** 并发请求共用一次刷新,避免同时打刷新接口或互相清缓存。 */
1246
+ static oauthRefreshInFlight = null;
591
1247
  /**
592
1248
  * 获取当前生效的 access token,并具备自动刷新能力:
593
- * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
1249
+ * - OAuth:未过期,或没有过期时间时,直接用缓存。过期且有 refreshToken 才刷新。
1250
+ * 请求路径不打开浏览器;需要重新授权时抛错,由 `auth login` 或 DevEco 降级处理。
594
1251
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
595
1252
  * - deveco:过期后重新解密本地登录态并 refresh 换取
596
1253
  *
597
- * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
1254
+ * force 跳过缓存(供 401 重试使用)。OAuth 在 force 时只走 refreshToken。
598
1255
  */
599
1256
  static async getAccessToken(force = false) {
600
1257
  const { config: config2, cache } = this.getStatus();
601
- return this.getToken(config2, cache, force);
602
- }
603
- static async getToken(cfg, cache, force = false) {
604
- 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) {
605
1262
  return cache.accessToken;
606
1263
  }
607
- 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) {
608
1287
  try {
609
- const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
610
- const expiresAt = Date.now() + refreshed.expireTime * 1e3;
611
- this.writeCache({
612
- accessToken: refreshed.accessToken,
613
- expiresAt,
614
- clientId: cfg.clientId,
615
- domain: cfg.domain,
616
- authMode: cfg.authMode,
617
- refreshToken: cache.refreshToken
618
- // 刷新接口不返回新 refreshToken,沿用旧值
619
- });
620
- return refreshed.accessToken;
1288
+ return await this.refreshCachedOAuth(cfg, cache);
621
1289
  } catch (e) {
622
- console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
623
- this.clearCache();
1290
+ if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache.accessToken && !interactive) {
1291
+ return cache.accessToken;
1292
+ }
1293
+ if (!interactive) throw e;
624
1294
  }
1295
+ } else if (!interactive) {
1296
+ throw new Error(NOT_LOGGED_IN);
625
1297
  }
626
- return this.acquire(cfg);
1298
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
1299
+ this.pendingOAuthLogin = void 0;
1300
+ });
1301
+ return this.pendingOAuthLogin;
627
1302
  }
628
1303
  /** 登录入口:按当前认证模式获取并缓存 token */
629
1304
  static async login() {
@@ -633,10 +1308,8 @@ var AuthManager = class {
633
1308
  /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
634
1309
  static async acquire(cfg) {
635
1310
  if (cfg.authMode === "oauth") {
636
- this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
637
- this.pendingOAuthLogin = void 0;
638
- });
639
- return this.pendingOAuthLogin;
1311
+ const cache = this.matchingCache(cfg, this.readCache());
1312
+ return this.getOAuthAccessToken(cfg, cache, false, true);
640
1313
  }
641
1314
  if (cfg.authMode === "deveco") {
642
1315
  try {
@@ -646,7 +1319,7 @@ var AuthManager = class {
646
1319
  const oauthConfig = getConfig("oauth");
647
1320
  const cache = this.matchingCache(oauthConfig, this.readCache());
648
1321
  console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
649
- return this.getToken(oauthConfig, cache);
1322
+ return this.getOAuthAccessToken(oauthConfig, cache, false, true);
650
1323
  }
651
1324
  }
652
1325
  if (cfg.authMode === "service_account") {
@@ -677,51 +1350,68 @@ var AuthManager = class {
677
1350
  }
678
1351
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
679
1352
  }
680
- /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
1353
+ /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器。同一进程只开一次。 */
681
1354
  static loginOAuth(cfg) {
682
1355
  return new Promise((resolve2, reject) => {
683
1356
  const redirectUri = cfg.oauth.redirectUri;
684
1357
  const port = Number(new URL(redirectUri).port || 80);
685
- const state = crypto2.randomBytes(32).toString("hex");
686
- 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) => {
687
1369
  try {
688
- 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"}`);
689
1371
  const code = url.searchParams.get("code");
690
1372
  const returnedState = url.searchParams.get("state");
691
- if (!code || returnedState !== state) {
692
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
693
- 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));
694
1383
  return;
695
1384
  }
696
1385
  const token = await AuthService.getOAuthToken(code, redirectUri);
697
- const expiresAt = Date.now() + token.expireTime * 1e3;
698
1386
  clearOAuthTeamIdCache();
699
1387
  this.writeCache({
700
1388
  accessToken: token.accessToken,
701
- expiresAt,
1389
+ expiresAt: resolveExpiresAt(token.expireTime),
702
1390
  clientId: cfg.clientId,
703
1391
  domain: cfg.domain,
704
1392
  authMode: cfg.authMode,
705
1393
  refreshToken: token.refreshToken
706
1394
  });
707
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
708
- 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>');
709
- server.close();
710
- resolve2(token.accessToken);
1395
+ sendLoginPage(res, "success");
1396
+ finish(void 0, token.accessToken);
711
1397
  } catch (err) {
712
- server.close();
713
- 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));
714
1401
  }
715
1402
  });
716
1403
  server.on("error", (err) => {
717
- server.close();
718
- 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);
719
1409
  });
720
1410
  server.listen(port, () => {
721
1411
  const authUrl = AuthService.buildAuthUrl(state);
722
1412
  console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
723
1413
  console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
724
- openBrowser(authUrl);
1414
+ launchBrowser(authUrl);
725
1415
  });
726
1416
  });
727
1417
  }
@@ -758,50 +1448,92 @@ var AuthManager = class {
758
1448
  static matchingCache(cfg, cache) {
759
1449
  return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
760
1450
  }
761
- 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) {
762
1460
  try {
763
- if (import_fs5.default.existsSync(this.cacheFile)) {
764
- const data = readPrivateFile(this.cacheFile);
765
- return JSON.parse(data);
766
- }
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;
767
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;
768
1480
  }
769
- 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;
770
1487
  }
771
1488
  static writeCache(cache) {
772
- try {
773
- writePrivateFile(this.cacheFile, JSON.stringify(cache, null, 2));
774
- } 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;
775
1495
  }
1496
+ writeVault(tokenFilePath(), next);
776
1497
  }
777
1498
  /**
778
1499
  * 清除缓存的 Token(登出)
779
1500
  */
780
1501
  static clearCache() {
781
1502
  clearOAuthTeamIdCache();
782
- try {
783
- if (import_fs5.default.existsSync(this.cacheFile)) {
784
- import_fs5.default.unlinkSync(this.cacheFile);
785
- return true;
786
- }
787
- return false;
788
- } catch (e) {
789
- return false;
790
- }
1503
+ return clearVault(tokenFilePath());
791
1504
  }
792
1505
  };
793
- function openBrowser(url) {
794
- const platform = process.platform;
795
- const cmd = platform === "darwin" ? "open" : platform === "win32" ? 'start ""' : "xdg-open";
796
- (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) => {
797
1516
  if (err) {
798
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");
799
1518
  }
800
1519
  });
801
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
+ }
802
1534
 
803
1535
  // src/core/request-source.ts
804
- var import_fs6 = __toESM(require("fs"));
1536
+ var import_fs7 = __toESM(require("fs"));
805
1537
  var import_path5 = __toESM(require("path"));
806
1538
  var REQUEST_SOURCE_HEADER = "Request-Source";
807
1539
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
@@ -942,7 +1674,7 @@ function getRequestSource() {
942
1674
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
943
1675
  }
944
1676
  function readVersion() {
945
- const fromBuild = injected(true ? "1.1.10" : void 0);
1677
+ const fromBuild = injected(true ? "1.1.11" : void 0);
946
1678
  if (fromBuild) return fromBuild;
947
1679
  const candidates = [
948
1680
  import_path5.default.join(__dirname, "..", "..", "package.json"),
@@ -950,7 +1682,7 @@ function readVersion() {
950
1682
  ];
951
1683
  for (const pkgPath of candidates) {
952
1684
  try {
953
- const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
1685
+ const pkg = JSON.parse(import_fs7.default.readFileSync(pkgPath, "utf8"));
954
1686
  if (pkg.version) return pkg.version;
955
1687
  } catch {
956
1688
  }
@@ -1044,7 +1776,7 @@ connectApiClient.interceptors.response.use(
1044
1776
  original._retry = true;
1045
1777
  try {
1046
1778
  const cfg = getConfig();
1047
- const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
1779
+ const newToken = await AuthManager.getAccessToken(true);
1048
1780
  if (!original.headers) {
1049
1781
  original.headers = {};
1050
1782
  }
@@ -1052,6 +1784,10 @@ connectApiClient.interceptors.response.use(
1052
1784
  if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1053
1785
  return connectApiClient(original);
1054
1786
  } catch (e) {
1787
+ if (e instanceof Error && e.message) {
1788
+ err.message = `${err.message}
1789
+ ${e.message}`;
1790
+ }
1055
1791
  return Promise.reject(err);
1056
1792
  }
1057
1793
  }
@@ -1405,7 +2141,7 @@ var ProjectService = class {
1405
2141
 
1406
2142
  // src/services/upload.ts
1407
2143
  var import_axios4 = __toESM(require("axios"));
1408
- var import_fs7 = __toESM(require("fs"));
2144
+ var import_fs8 = __toESM(require("fs"));
1409
2145
  var import_path6 = __toESM(require("path"));
1410
2146
  function pickObjectId(res) {
1411
2147
  return res.urlInfo?.objectId || res.objectId;
@@ -1445,7 +2181,7 @@ var UploadService = class {
1445
2181
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1446
2182
  */
1447
2183
  static async uploadFile(options) {
1448
- const stat = import_fs7.default.statSync(options.filePath);
2184
+ const stat = import_fs8.default.statSync(options.filePath);
1449
2185
  const fileName = import_path6.default.basename(options.filePath) || "unknown";
1450
2186
  if (stat.size < 5 * 1024 * 1024) {
1451
2187
  return this.uploadSingleFile(options, fileName, stat.size);
@@ -1487,7 +2223,7 @@ var UploadService = class {
1487
2223
  );
1488
2224
  }
1489
2225
  const { url, headers } = urlRes.urlInfo;
1490
- const fileStream = import_fs7.default.createReadStream(options.filePath);
2226
+ const fileStream = import_fs8.default.createReadStream(options.filePath);
1491
2227
  await import_axios4.default.put(url, fileStream, {
1492
2228
  headers: this.buildObsPutHeaders(headers, contentLength),
1493
2229
  maxBodyLength: Infinity,
@@ -1528,7 +2264,7 @@ var UploadService = class {
1528
2264
  if (!uploadInfoMap) {
1529
2265
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1530
2266
  }
1531
- const fd = import_fs7.default.openSync(options.filePath, "r");
2267
+ const fd = import_fs8.default.openSync(options.filePath, "r");
1532
2268
  const composeReqBody = {};
1533
2269
  for (let i = 1; i <= partsCount; i++) {
1534
2270
  const propKey = `additionalProp${i}`;
@@ -1537,7 +2273,7 @@ var UploadService = class {
1537
2273
  const end = Math.min(start + partSize, fileSize);
1538
2274
  const length = end - start;
1539
2275
  const buffer = Buffer.alloc(length);
1540
- import_fs7.default.readSync(fd, buffer, 0, length, start);
2276
+ import_fs8.default.readSync(fd, buffer, 0, length, start);
1541
2277
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1542
2278
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1543
2279
  maxBodyLength: Infinity,
@@ -1549,7 +2285,7 @@ var UploadService = class {
1549
2285
  etag
1550
2286
  };
1551
2287
  }
1552
- import_fs7.default.closeSync(fd);
2288
+ import_fs8.default.closeSync(fd);
1553
2289
  await this.composeMultipart({
1554
2290
  objectId,
1555
2291
  nspUploadId,
@@ -1680,10 +2416,13 @@ var ProvisionService = class {
1680
2416
  // Annotate the CommonJS export names for ESM import in node:
1681
2417
  0 && (module.exports = {
1682
2418
  AuthService,
2419
+ OAuthRefreshRejectedError,
1683
2420
  ProjectService,
1684
2421
  ProvisionService,
1685
2422
  PublishService,
1686
2423
  UploadService,
1687
2424
  connectApiClient,
1688
- getConfig
2425
+ getConfig,
2426
+ isDefinitiveOAuthRefreshFailure,
2427
+ normalizeOAuthToken
1689
2428
  });