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/README.md +17 -9
- package/dist/cli.js +1404 -236
- package/dist/index.d.mts +21 -2
- package/dist/index.d.ts +21 -2
- package/dist/index.js +870 -139
- package/dist/index.mjs +843 -115
- package/package.json +4 -2
package/dist/index.mjs
CHANGED
|
@@ -104,6 +104,44 @@ function getConfig(authMode = process.env.AGC_AUTH_MODE ?? "deveco") {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
// src/services/auth.ts
|
|
107
|
+
var OAuthRefreshRejectedError = class extends Error {
|
|
108
|
+
constructor(message) {
|
|
109
|
+
super(message);
|
|
110
|
+
this.name = "OAuthRefreshRejectedError";
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
function normalizeOAuthToken(data, previousRefreshToken) {
|
|
114
|
+
const raw = data && typeof data === "object" ? data : {};
|
|
115
|
+
const accessToken = pickString(raw, "accessToken", "access_token");
|
|
116
|
+
if (!accessToken) {
|
|
117
|
+
throw new Error("Authentication failed");
|
|
118
|
+
}
|
|
119
|
+
const refreshToken = pickString(raw, "refreshToken", "refresh_token") || previousRefreshToken?.trim() || "";
|
|
120
|
+
return {
|
|
121
|
+
accessToken,
|
|
122
|
+
expireTime: pickExpireSeconds(raw),
|
|
123
|
+
refreshToken: refreshToken || void 0
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function isDefinitiveOAuthRefreshFailure(err) {
|
|
127
|
+
if (err instanceof OAuthRefreshRejectedError) return true;
|
|
128
|
+
const status = err?.response?.status;
|
|
129
|
+
return typeof status === "number" && status >= 400 && status < 500;
|
|
130
|
+
}
|
|
131
|
+
function pickString(raw, ...keys) {
|
|
132
|
+
for (const key of keys) {
|
|
133
|
+
const value = raw[key];
|
|
134
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
135
|
+
}
|
|
136
|
+
return "";
|
|
137
|
+
}
|
|
138
|
+
function pickExpireSeconds(raw) {
|
|
139
|
+
for (const key of ["expireTime", "expiresTime", "expiresIn", "expires_in"]) {
|
|
140
|
+
const value = Number(raw[key]);
|
|
141
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
142
|
+
}
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
107
145
|
var SA_AUD = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
|
|
108
146
|
var SA_JWT_TTL_SEC = 3600;
|
|
109
147
|
var DEVECO_CHECK_URL = process.env.AGC_DEVECO_CHECK_URL || "https://cn.devecostudio.huawei.com/authrouter/auth/api/jwToken/check";
|
|
@@ -194,7 +232,8 @@ var AuthService = class {
|
|
|
194
232
|
if (!res.data.ret || res.data.ret.code !== 0) {
|
|
195
233
|
throw new Error(res.data.ret?.msg || "Authentication failed");
|
|
196
234
|
}
|
|
197
|
-
|
|
235
|
+
const token = normalizeOAuthToken(res.data);
|
|
236
|
+
return { ret: res.data.ret, accessToken: token.accessToken, expireTime: token.expireTime, refreshToken: token.refreshToken };
|
|
198
237
|
} catch (err) {
|
|
199
238
|
if (err instanceof Error && err.name === "AbortError") {
|
|
200
239
|
throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
|
|
@@ -219,9 +258,15 @@ var AuthService = class {
|
|
|
219
258
|
signal: controller.signal
|
|
220
259
|
});
|
|
221
260
|
if (!res.data.ret || res.data.ret.code !== 0) {
|
|
222
|
-
throw new
|
|
261
|
+
throw new OAuthRefreshRejectedError(res.data.ret?.msg || "Refresh failed");
|
|
223
262
|
}
|
|
224
|
-
|
|
263
|
+
const token = normalizeOAuthToken(res.data, refreshToken);
|
|
264
|
+
return {
|
|
265
|
+
ret: res.data.ret,
|
|
266
|
+
accessToken: token.accessToken,
|
|
267
|
+
expireTime: token.expireTime,
|
|
268
|
+
refreshToken: token.refreshToken
|
|
269
|
+
};
|
|
225
270
|
} catch (err) {
|
|
226
271
|
if (err instanceof Error && err.name === "AbortError") {
|
|
227
272
|
throw new Error("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
|
|
@@ -279,6 +324,21 @@ function normalizePem(privateKey) {
|
|
|
279
324
|
// src/core/http.ts
|
|
280
325
|
import axios3 from "axios";
|
|
281
326
|
|
|
327
|
+
// src/core/oauth-team.ts
|
|
328
|
+
import axios2 from "axios";
|
|
329
|
+
|
|
330
|
+
// src/core/token-vault.ts
|
|
331
|
+
import * as crypto2 from "crypto";
|
|
332
|
+
import fs4 from "fs";
|
|
333
|
+
import os2 from "os";
|
|
334
|
+
import path3 from "path";
|
|
335
|
+
|
|
336
|
+
// src/core/key-store.ts
|
|
337
|
+
import { execFileSync, spawnSync } from "child_process";
|
|
338
|
+
import fs3 from "fs";
|
|
339
|
+
import os from "os";
|
|
340
|
+
import path2 from "path";
|
|
341
|
+
|
|
282
342
|
// src/core/private-file.ts
|
|
283
343
|
import fs2 from "fs";
|
|
284
344
|
function restrictPermissions(fd) {
|
|
@@ -304,28 +364,479 @@ function writePrivateFile(file, contents) {
|
|
|
304
364
|
}
|
|
305
365
|
}
|
|
306
366
|
|
|
367
|
+
// src/core/key-store.ts
|
|
368
|
+
var KEYCHAIN_SERVICE = "connect-api-cli";
|
|
369
|
+
var KEYCHAIN_ACCOUNT = "token-key";
|
|
370
|
+
var KEYCHAIN_SLOT = `${KEYCHAIN_SERVICE}\0${KEYCHAIN_ACCOUNT}`;
|
|
371
|
+
var SECRET_SLOT = "connect-api-cli\0token-key";
|
|
372
|
+
var unlocked = /* @__PURE__ */ new Map();
|
|
373
|
+
function tokenKeyPath(tokenFile) {
|
|
374
|
+
return path2.join(path2.dirname(tokenFile), ".connect-api-cli-token.key");
|
|
375
|
+
}
|
|
376
|
+
function forgetKeyFile(keyFile) {
|
|
377
|
+
unlocked.delete(cacheId("dpapi", keyFile));
|
|
378
|
+
unlocked.delete(cacheId("file", keyFile));
|
|
379
|
+
}
|
|
380
|
+
function createDefaultKeyStore(tokenFile) {
|
|
381
|
+
if (process.platform === "win32") return createDpapiKeyStore(tokenKeyPath(tokenFile));
|
|
382
|
+
if (process.platform === "darwin") return createKeychainKeyStore();
|
|
383
|
+
return createLinuxKeyStore(tokenKeyPath(tokenFile));
|
|
384
|
+
}
|
|
385
|
+
function keyStoreById(id, tokenFile) {
|
|
386
|
+
const keyFile = tokenKeyPath(tokenFile);
|
|
387
|
+
if (id === "dpapi") return createDpapiKeyStore(keyFile);
|
|
388
|
+
if (id === "keychain") return createKeychainKeyStore();
|
|
389
|
+
if (id === "secret-service") return createSecretServiceKeyStore();
|
|
390
|
+
if (id === "file") return createFileKeyStore(keyFile);
|
|
391
|
+
throw new Error(`Unknown token key protection: ${id}`);
|
|
392
|
+
}
|
|
393
|
+
function createFileKeyStore(keyFile) {
|
|
394
|
+
return {
|
|
395
|
+
id: "file",
|
|
396
|
+
load: () => readPrefixedKey("file", keyFile, "raw:"),
|
|
397
|
+
save: (key) => writePrefixedKey("file", keyFile, "raw:", key),
|
|
398
|
+
clear: () => removePrefixedKey("file", keyFile)
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
function createDpapiKeyStore(keyFile) {
|
|
402
|
+
return {
|
|
403
|
+
id: "dpapi",
|
|
404
|
+
load: () => {
|
|
405
|
+
const cached = recall("dpapi", keyFile);
|
|
406
|
+
if (cached) return cached;
|
|
407
|
+
const wrapped = readPrefixed(keyFile, "dpapi:");
|
|
408
|
+
if (!wrapped) return null;
|
|
409
|
+
const key = decodeKey(dpapi("unprotect", wrapped));
|
|
410
|
+
if (!key) return null;
|
|
411
|
+
remember("dpapi", keyFile, key);
|
|
412
|
+
return key;
|
|
413
|
+
},
|
|
414
|
+
save: (key) => {
|
|
415
|
+
assertKey(key);
|
|
416
|
+
writePrefixed(keyFile, "dpapi:", dpapi("protect", key.toString("base64")));
|
|
417
|
+
remember("dpapi", keyFile, key);
|
|
418
|
+
},
|
|
419
|
+
clear: () => removePrefixedKey("dpapi", keyFile)
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
function createKeychainKeyStore() {
|
|
423
|
+
return {
|
|
424
|
+
id: "keychain",
|
|
425
|
+
load: () => keychainLoad(),
|
|
426
|
+
save: (key) => keychainSave(key),
|
|
427
|
+
clear: () => keychainClear()
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function createSecretServiceKeyStore() {
|
|
431
|
+
return {
|
|
432
|
+
id: "secret-service",
|
|
433
|
+
load: () => secretLookup(),
|
|
434
|
+
save: (key) => {
|
|
435
|
+
if (!secretStore(key)) {
|
|
436
|
+
throw new Error("Failed to store the token key in the Secret Service.");
|
|
437
|
+
}
|
|
438
|
+
},
|
|
439
|
+
clear: () => secretClear()
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
function createLinuxKeyStore(keyFile) {
|
|
443
|
+
const store = {
|
|
444
|
+
id: "file",
|
|
445
|
+
load() {
|
|
446
|
+
if (hasSecretTool()) {
|
|
447
|
+
const key2 = secretLookup();
|
|
448
|
+
if (key2) {
|
|
449
|
+
store.id = "secret-service";
|
|
450
|
+
return key2;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const key = readPrefixedKey("file", keyFile, "raw:");
|
|
454
|
+
if (key) store.id = "file";
|
|
455
|
+
return key;
|
|
456
|
+
},
|
|
457
|
+
save(key) {
|
|
458
|
+
if (hasSecretTool() && secretStore(key)) {
|
|
459
|
+
store.id = "secret-service";
|
|
460
|
+
removePrefixedKey("file", keyFile);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
store.id = "file";
|
|
464
|
+
writePrefixedKey("file", keyFile, "raw:", key);
|
|
465
|
+
},
|
|
466
|
+
clear() {
|
|
467
|
+
secretClear();
|
|
468
|
+
removePrefixedKey("file", keyFile);
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
return store;
|
|
472
|
+
}
|
|
473
|
+
function cacheId(id, slot) {
|
|
474
|
+
return `${id}\0${slot}`;
|
|
475
|
+
}
|
|
476
|
+
function remember(id, slot, key) {
|
|
477
|
+
unlocked.set(cacheId(id, slot), Buffer.from(key));
|
|
478
|
+
}
|
|
479
|
+
function recall(id, slot) {
|
|
480
|
+
const hit = unlocked.get(cacheId(id, slot));
|
|
481
|
+
return hit ? Buffer.from(hit) : null;
|
|
482
|
+
}
|
|
483
|
+
function forget(id, slot) {
|
|
484
|
+
unlocked.delete(cacheId(id, slot));
|
|
485
|
+
}
|
|
486
|
+
function assertKey(key) {
|
|
487
|
+
if (key.length !== 32) throw new Error("Token key must be 32 bytes");
|
|
488
|
+
}
|
|
489
|
+
function decodeKey(b64) {
|
|
490
|
+
const key = Buffer.from(b64, "base64");
|
|
491
|
+
return key.length === 32 ? key : null;
|
|
492
|
+
}
|
|
493
|
+
function readPrefixed(keyFile, prefix) {
|
|
494
|
+
if (!fs3.existsSync(keyFile)) return null;
|
|
495
|
+
const text = fs3.readFileSync(keyFile, "utf8").replace(/^\uFEFF/, "").trim();
|
|
496
|
+
if (!text.startsWith(prefix)) return null;
|
|
497
|
+
return text.slice(prefix.length);
|
|
498
|
+
}
|
|
499
|
+
function readPrefixedKey(id, keyFile, prefix) {
|
|
500
|
+
const cached = recall(id, keyFile);
|
|
501
|
+
if (cached) return cached;
|
|
502
|
+
const b64 = readPrefixed(keyFile, prefix);
|
|
503
|
+
if (!b64) return null;
|
|
504
|
+
const key = decodeKey(b64);
|
|
505
|
+
if (!key) return null;
|
|
506
|
+
remember(id, keyFile, key);
|
|
507
|
+
return key;
|
|
508
|
+
}
|
|
509
|
+
function writePrefixed(keyFile, prefix, payload) {
|
|
510
|
+
fs3.mkdirSync(path2.dirname(keyFile), { recursive: true });
|
|
511
|
+
writePrivateFile(keyFile, `${prefix}${payload}
|
|
512
|
+
`);
|
|
513
|
+
}
|
|
514
|
+
function writePrefixedKey(id, keyFile, prefix, key) {
|
|
515
|
+
assertKey(key);
|
|
516
|
+
writePrefixed(keyFile, prefix, key.toString("base64"));
|
|
517
|
+
remember(id, keyFile, key);
|
|
518
|
+
}
|
|
519
|
+
function removePrefixedKey(id, keyFile) {
|
|
520
|
+
forget(id, keyFile);
|
|
521
|
+
fs3.rmSync(keyFile, { force: true });
|
|
522
|
+
}
|
|
523
|
+
var DPAPI_SCRIPT = `
|
|
524
|
+
$ErrorActionPreference = 'Stop'
|
|
525
|
+
Add-Type -AssemblyName System.Security
|
|
526
|
+
$utf8 = New-Object System.Text.UTF8Encoding $false
|
|
527
|
+
$b64 = [System.IO.File]::ReadAllText($env:CONNECT_API_SECRET_IN).Trim()
|
|
528
|
+
$bytes = [System.Convert]::FromBase64String($b64)
|
|
529
|
+
$entropy = [System.Text.Encoding]::UTF8.GetBytes('connect-api-cli-token-v1')
|
|
530
|
+
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
|
|
531
|
+
if ($env:CONNECT_API_SECRET_OP -eq 'protect') {
|
|
532
|
+
$outBytes = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope)
|
|
533
|
+
} elseif ($env:CONNECT_API_SECRET_OP -eq 'unprotect') {
|
|
534
|
+
$outBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope)
|
|
535
|
+
} else {
|
|
536
|
+
throw 'bad op'
|
|
537
|
+
}
|
|
538
|
+
[System.IO.File]::WriteAllText($env:CONNECT_API_SECRET_OUT, [System.Convert]::ToBase64String($outBytes), $utf8)
|
|
539
|
+
`;
|
|
540
|
+
function powershellExe() {
|
|
541
|
+
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
542
|
+
const candidate = path2.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
543
|
+
return fs3.existsSync(candidate) ? candidate : "powershell.exe";
|
|
544
|
+
}
|
|
545
|
+
function dpapi(op, payloadB64) {
|
|
546
|
+
const dir = fs3.mkdtempSync(path2.join(os.tmpdir(), "connect-api-cli-"));
|
|
547
|
+
const inPath = path2.join(dir, "in.txt");
|
|
548
|
+
const outPath = path2.join(dir, "out.txt");
|
|
549
|
+
try {
|
|
550
|
+
fs3.writeFileSync(inPath, payloadB64, { encoding: "utf8", mode: 384 });
|
|
551
|
+
const encoded = Buffer.from(DPAPI_SCRIPT, "utf16le").toString("base64");
|
|
552
|
+
try {
|
|
553
|
+
execFileSync(powershellExe(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
|
|
554
|
+
env: {
|
|
555
|
+
...process.env,
|
|
556
|
+
CONNECT_API_SECRET_IN: inPath,
|
|
557
|
+
CONNECT_API_SECRET_OUT: outPath,
|
|
558
|
+
CONNECT_API_SECRET_OP: op
|
|
559
|
+
},
|
|
560
|
+
windowsHide: true,
|
|
561
|
+
timeout: 2e4,
|
|
562
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
563
|
+
encoding: "utf8"
|
|
564
|
+
});
|
|
565
|
+
} catch (e) {
|
|
566
|
+
const stderr = typeof e.stderr === "string" ? e.stderr.trim().slice(0, 400) : "";
|
|
567
|
+
throw new Error(`Windows DPAPI ${op} failed${stderr ? `: ${stderr}` : ""}`);
|
|
568
|
+
}
|
|
569
|
+
if (!fs3.existsSync(outPath)) throw new Error(`Windows DPAPI ${op} failed: no output`);
|
|
570
|
+
return fs3.readFileSync(outPath, "utf8").replace(/^\uFEFF/, "").trim();
|
|
571
|
+
} finally {
|
|
572
|
+
fs3.rmSync(dir, { recursive: true, force: true });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
function keychainLoad() {
|
|
576
|
+
const cached = recall("keychain", KEYCHAIN_SLOT);
|
|
577
|
+
if (cached) return cached;
|
|
578
|
+
try {
|
|
579
|
+
const out = execFileSync("security", [
|
|
580
|
+
"find-generic-password",
|
|
581
|
+
"-s",
|
|
582
|
+
KEYCHAIN_SERVICE,
|
|
583
|
+
"-a",
|
|
584
|
+
KEYCHAIN_ACCOUNT,
|
|
585
|
+
"-w"
|
|
586
|
+
], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
587
|
+
const key = decodeKey(out.trim());
|
|
588
|
+
if (!key) return null;
|
|
589
|
+
remember("keychain", KEYCHAIN_SLOT, key);
|
|
590
|
+
return key;
|
|
591
|
+
} catch (e) {
|
|
592
|
+
const status = e.status;
|
|
593
|
+
if (status === 44) return null;
|
|
594
|
+
throw new Error("macOS Keychain read failed");
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function keychainSave(key) {
|
|
598
|
+
assertKey(key);
|
|
599
|
+
execFileSync("security", [
|
|
600
|
+
"add-generic-password",
|
|
601
|
+
"-U",
|
|
602
|
+
"-A",
|
|
603
|
+
"-s",
|
|
604
|
+
KEYCHAIN_SERVICE,
|
|
605
|
+
"-a",
|
|
606
|
+
KEYCHAIN_ACCOUNT,
|
|
607
|
+
"-w",
|
|
608
|
+
key.toString("base64")
|
|
609
|
+
], { timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
610
|
+
remember("keychain", KEYCHAIN_SLOT, key);
|
|
611
|
+
}
|
|
612
|
+
function keychainClear() {
|
|
613
|
+
forget("keychain", KEYCHAIN_SLOT);
|
|
614
|
+
try {
|
|
615
|
+
execFileSync("security", [
|
|
616
|
+
"delete-generic-password",
|
|
617
|
+
"-s",
|
|
618
|
+
KEYCHAIN_SERVICE,
|
|
619
|
+
"-a",
|
|
620
|
+
KEYCHAIN_ACCOUNT
|
|
621
|
+
], { timeout: 1e4, stdio: "ignore" });
|
|
622
|
+
} catch {
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
var secretToolAvailable;
|
|
626
|
+
function hasSecretTool() {
|
|
627
|
+
if (process.platform === "win32" || process.platform === "darwin") return false;
|
|
628
|
+
if (secretToolAvailable !== void 0) return secretToolAvailable;
|
|
629
|
+
const r = spawnSync("secret-tool", ["--version"], { stdio: "ignore" });
|
|
630
|
+
const missing = !!r.error && r.error.code === "ENOENT";
|
|
631
|
+
secretToolAvailable = !missing;
|
|
632
|
+
return secretToolAvailable;
|
|
633
|
+
}
|
|
634
|
+
function secretLookup() {
|
|
635
|
+
const cached = recall("secret-service", SECRET_SLOT);
|
|
636
|
+
if (cached) return cached;
|
|
637
|
+
const r = spawnSync("secret-tool", [
|
|
638
|
+
"lookup",
|
|
639
|
+
"service",
|
|
640
|
+
"connect-api-cli",
|
|
641
|
+
"username",
|
|
642
|
+
"token-key"
|
|
643
|
+
], { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
644
|
+
if (r.error || r.status !== 0) return null;
|
|
645
|
+
const key = decodeKey((r.stdout || "").trim());
|
|
646
|
+
if (!key) return null;
|
|
647
|
+
remember("secret-service", SECRET_SLOT, key);
|
|
648
|
+
return key;
|
|
649
|
+
}
|
|
650
|
+
function secretStore(key) {
|
|
651
|
+
assertKey(key);
|
|
652
|
+
const r = spawnSync("secret-tool", [
|
|
653
|
+
"store",
|
|
654
|
+
"--label=connect-api-cli token key",
|
|
655
|
+
"service",
|
|
656
|
+
"connect-api-cli",
|
|
657
|
+
"username",
|
|
658
|
+
"token-key"
|
|
659
|
+
], {
|
|
660
|
+
input: key.toString("base64"),
|
|
661
|
+
encoding: "utf8",
|
|
662
|
+
timeout: 1e4,
|
|
663
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
664
|
+
});
|
|
665
|
+
if (r.status !== 0) return false;
|
|
666
|
+
remember("secret-service", SECRET_SLOT, key);
|
|
667
|
+
return true;
|
|
668
|
+
}
|
|
669
|
+
function secretClear() {
|
|
670
|
+
forget("secret-service", SECRET_SLOT);
|
|
671
|
+
spawnSync("secret-tool", [
|
|
672
|
+
"clear",
|
|
673
|
+
"service",
|
|
674
|
+
"connect-api-cli",
|
|
675
|
+
"username",
|
|
676
|
+
"token-key"
|
|
677
|
+
], { stdio: "ignore", timeout: 1e4 });
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// src/core/token-vault.ts
|
|
681
|
+
var KTY = "connect-api-cli-secret";
|
|
682
|
+
var TokenDecryptError = class extends Error {
|
|
683
|
+
constructor() {
|
|
684
|
+
super("Token cache authentication failed");
|
|
685
|
+
this.name = "TokenDecryptError";
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
function tokenFilePath() {
|
|
689
|
+
return path3.join(os2.homedir(), ".connect-api-cli-token.json");
|
|
690
|
+
}
|
|
691
|
+
function readVault(file, store) {
|
|
692
|
+
if (!fs4.existsSync(file)) return null;
|
|
693
|
+
let parsed;
|
|
694
|
+
try {
|
|
695
|
+
parsed = JSON.parse(readPrivateFile(file));
|
|
696
|
+
} catch {
|
|
697
|
+
return null;
|
|
698
|
+
}
|
|
699
|
+
if (isLegacyToken(parsed)) {
|
|
700
|
+
writeVault(file, parsed, store);
|
|
701
|
+
return parsed;
|
|
702
|
+
}
|
|
703
|
+
if (!isEnvelope(parsed)) return null;
|
|
704
|
+
const keys = store ?? storeForWrap(parsed.wrap, file);
|
|
705
|
+
if (!keys) return null;
|
|
706
|
+
const key = keys.load();
|
|
707
|
+
if (!key) return null;
|
|
708
|
+
try {
|
|
709
|
+
return JSON.parse(decryptJson(parsed, key));
|
|
710
|
+
} catch (e) {
|
|
711
|
+
if (e instanceof TokenDecryptError) return null;
|
|
712
|
+
throw e;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
function writeVault(file, value, store) {
|
|
716
|
+
const keys = store ?? storeForWrite(file);
|
|
717
|
+
let key = keys.load();
|
|
718
|
+
if (!key) {
|
|
719
|
+
key = crypto2.randomBytes(32);
|
|
720
|
+
keys.save(key);
|
|
721
|
+
}
|
|
722
|
+
const envelope = {
|
|
723
|
+
kty: KTY,
|
|
724
|
+
v: 1,
|
|
725
|
+
alg: "A256GCM",
|
|
726
|
+
wrap: keys.id,
|
|
727
|
+
...encryptJson(JSON.stringify(value), key)
|
|
728
|
+
};
|
|
729
|
+
atomicWrite(file, `${JSON.stringify(envelope, null, 2)}
|
|
730
|
+
`);
|
|
731
|
+
}
|
|
732
|
+
function clearVault(file) {
|
|
733
|
+
const wrap = peekWrap(file);
|
|
734
|
+
let existed = fs4.existsSync(file);
|
|
735
|
+
fs4.rmSync(file, { force: true });
|
|
736
|
+
if (wrap) {
|
|
737
|
+
try {
|
|
738
|
+
keyStoreById(wrap, file).clear();
|
|
739
|
+
} catch {
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const keyFile = tokenKeyPath(file);
|
|
743
|
+
if (fs4.existsSync(keyFile)) {
|
|
744
|
+
fs4.rmSync(keyFile, { force: true });
|
|
745
|
+
existed = true;
|
|
746
|
+
}
|
|
747
|
+
forgetKeyFile(keyFile);
|
|
748
|
+
return existed;
|
|
749
|
+
}
|
|
750
|
+
function storeForWrite(file) {
|
|
751
|
+
const wrap = peekWrap(file);
|
|
752
|
+
if (wrap) {
|
|
753
|
+
const existing = storeForWrap(wrap, file);
|
|
754
|
+
if (existing?.load()) return existing;
|
|
755
|
+
}
|
|
756
|
+
return createDefaultKeyStore(file);
|
|
757
|
+
}
|
|
758
|
+
function storeForWrap(wrap, file) {
|
|
759
|
+
try {
|
|
760
|
+
return keyStoreById(wrap, file);
|
|
761
|
+
} catch {
|
|
762
|
+
return null;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
function peekWrap(file) {
|
|
766
|
+
if (!fs4.existsSync(file)) return null;
|
|
767
|
+
try {
|
|
768
|
+
const parsed = JSON.parse(readPrivateFile(file));
|
|
769
|
+
if (parsed?.kty === KTY && typeof parsed.wrap === "string") return parsed.wrap;
|
|
770
|
+
} catch {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
return null;
|
|
774
|
+
}
|
|
775
|
+
function isLegacyToken(value) {
|
|
776
|
+
if (!value || typeof value !== "object") return false;
|
|
777
|
+
const rec = value;
|
|
778
|
+
return typeof rec.accessToken === "string" && rec.kty !== KTY;
|
|
779
|
+
}
|
|
780
|
+
function isEnvelope(value) {
|
|
781
|
+
if (!value || typeof value !== "object") return false;
|
|
782
|
+
const v = value;
|
|
783
|
+
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";
|
|
784
|
+
}
|
|
785
|
+
function encryptJson(plain, key) {
|
|
786
|
+
const iv = crypto2.randomBytes(12);
|
|
787
|
+
const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
|
|
788
|
+
const ct = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
|
|
789
|
+
return {
|
|
790
|
+
iv: iv.toString("base64"),
|
|
791
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
792
|
+
ct: ct.toString("base64")
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
function decryptJson(env, key) {
|
|
796
|
+
try {
|
|
797
|
+
const decipher = crypto2.createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
|
|
798
|
+
decipher.setAuthTag(Buffer.from(env.tag, "base64"));
|
|
799
|
+
return Buffer.concat([
|
|
800
|
+
decipher.update(Buffer.from(env.ct, "base64")),
|
|
801
|
+
decipher.final()
|
|
802
|
+
]).toString("utf8");
|
|
803
|
+
} catch {
|
|
804
|
+
throw new TokenDecryptError();
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
function atomicWrite(file, contents) {
|
|
808
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
809
|
+
try {
|
|
810
|
+
writePrivateFile(tmp, contents);
|
|
811
|
+
try {
|
|
812
|
+
if (fs4.existsSync(file)) fs4.unlinkSync(file);
|
|
813
|
+
fs4.renameSync(tmp, file);
|
|
814
|
+
} catch {
|
|
815
|
+
writePrivateFile(file, contents);
|
|
816
|
+
fs4.rmSync(tmp, { force: true });
|
|
817
|
+
}
|
|
818
|
+
} catch (e) {
|
|
819
|
+
fs4.rmSync(tmp, { force: true });
|
|
820
|
+
throw e;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
307
824
|
// src/core/oauth-team.ts
|
|
308
|
-
import axios2 from "axios";
|
|
309
|
-
import fs3 from "fs";
|
|
310
|
-
import path2 from "path";
|
|
311
|
-
import os from "os";
|
|
312
|
-
var TOKEN_FILE = path2.join(os.homedir(), ".connect-api-cli-token.json");
|
|
313
825
|
var cachedTeamId;
|
|
314
826
|
function readPersistedTeamId() {
|
|
315
827
|
try {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
return data.teamId || void 0;
|
|
828
|
+
const data = readVault(tokenFilePath());
|
|
829
|
+
return data?.teamId || void 0;
|
|
319
830
|
} catch {
|
|
320
831
|
return void 0;
|
|
321
832
|
}
|
|
322
833
|
}
|
|
323
834
|
function writePersistedTeamId(teamId) {
|
|
324
835
|
try {
|
|
325
|
-
|
|
326
|
-
|
|
836
|
+
const data = readVault(tokenFilePath());
|
|
837
|
+
if (!data) return;
|
|
327
838
|
data.teamId = teamId;
|
|
328
|
-
|
|
839
|
+
writeVault(tokenFilePath(), data);
|
|
329
840
|
} catch {
|
|
330
841
|
}
|
|
331
842
|
}
|
|
@@ -333,8 +844,8 @@ async function resolveOAuthTeamId(cfg, accessToken) {
|
|
|
333
844
|
if (cfg.teamId) {
|
|
334
845
|
return cfg.teamId;
|
|
335
846
|
}
|
|
336
|
-
if (cachedTeamId
|
|
337
|
-
return cachedTeamId
|
|
847
|
+
if (cachedTeamId) {
|
|
848
|
+
return cachedTeamId;
|
|
338
849
|
}
|
|
339
850
|
const persisted = readPersistedTeamId();
|
|
340
851
|
if (persisted) {
|
|
@@ -352,33 +863,25 @@ async function resolveOAuthTeamId(cfg, accessToken) {
|
|
|
352
863
|
maxRedirects: 0
|
|
353
864
|
}
|
|
354
865
|
);
|
|
355
|
-
const teams = res.data.teams || [];
|
|
356
866
|
if (res.data.ret && res.data.ret.code !== 0) {
|
|
357
867
|
throw new Error(
|
|
358
868
|
`Failed to list teams for OAuth teamId: ${res.data.ret.msg || JSON.stringify(res.data.ret)}`
|
|
359
869
|
);
|
|
360
870
|
}
|
|
361
|
-
|
|
362
|
-
|
|
871
|
+
const firstTeam = res.data.teams?.[0];
|
|
872
|
+
if (!firstTeam?.id) {
|
|
363
873
|
throw new Error("OAuth account has no teams. Cannot set teamId for API calls.");
|
|
364
874
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
return cachedTeamId;
|
|
369
|
-
}
|
|
370
|
-
cachedTeamId = null;
|
|
371
|
-
const preview = teams.slice(0, 8).map((t) => `${t.id}${t.name ? `(${t.name})` : ""}`).join(", ");
|
|
372
|
-
throw new Error(
|
|
373
|
-
`Multiple teams found (${teams.length}). Set AGC_TEAM_ID to one of: ${preview}`
|
|
374
|
-
);
|
|
875
|
+
cachedTeamId = firstTeam.id;
|
|
876
|
+
writePersistedTeamId(cachedTeamId);
|
|
877
|
+
return cachedTeamId;
|
|
375
878
|
}
|
|
376
879
|
function clearOAuthTeamIdCache() {
|
|
377
880
|
cachedTeamId = void 0;
|
|
378
881
|
}
|
|
379
882
|
|
|
380
883
|
// src/core/deveco-token.ts
|
|
381
|
-
import { createDecipheriv } from "crypto";
|
|
884
|
+
import { createDecipheriv as createDecipheriv2 } from "crypto";
|
|
382
885
|
import { existsSync, readFileSync } from "fs";
|
|
383
886
|
import { homedir } from "os";
|
|
384
887
|
import { join, resolve } from "path";
|
|
@@ -390,7 +893,7 @@ var SOURCE_APP_NAMES = {
|
|
|
390
893
|
"deveco-code": "deveco"
|
|
391
894
|
};
|
|
392
895
|
function decryptAesGcm(ciphertext, key, iv, authTag) {
|
|
393
|
-
const decipher =
|
|
896
|
+
const decipher = createDecipheriv2(ALGORITHM, key, iv);
|
|
394
897
|
decipher.setAuthTag(authTag);
|
|
395
898
|
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
396
899
|
}
|
|
@@ -543,53 +1046,214 @@ function loadDevecoLocalToken(source, authDir) {
|
|
|
543
1046
|
return { jwt, expMs, location };
|
|
544
1047
|
}
|
|
545
1048
|
|
|
1049
|
+
// src/core/login-page.ts
|
|
1050
|
+
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>`;
|
|
1051
|
+
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>`;
|
|
1052
|
+
var PAGES = {
|
|
1053
|
+
success: {
|
|
1054
|
+
icon: SUCCESS_ICON,
|
|
1055
|
+
title: "\u767B\u5F55\u6210\u529F",
|
|
1056
|
+
message: "\u6388\u6743\u5DF2\u5B8C\u6210\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3\u5E76\u56DE\u5230\u7EC8\u7AEF",
|
|
1057
|
+
bgGradient: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
|
|
1058
|
+
},
|
|
1059
|
+
failed: {
|
|
1060
|
+
icon: FAILED_ICON,
|
|
1061
|
+
title: "\u767B\u5F55\u5931\u8D25",
|
|
1062
|
+
message: "\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5",
|
|
1063
|
+
bgGradient: "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)"
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
var TEMPLATE = `<!DOCTYPE html>
|
|
1067
|
+
<html lang="zh-CN">
|
|
1068
|
+
<head>
|
|
1069
|
+
<meta charset="utf-8">
|
|
1070
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1071
|
+
<title>{{TITLE}}</title>
|
|
1072
|
+
<style>
|
|
1073
|
+
* { box-sizing: border-box; }
|
|
1074
|
+
body {
|
|
1075
|
+
margin: 0;
|
|
1076
|
+
min-height: 100vh;
|
|
1077
|
+
display: flex;
|
|
1078
|
+
align-items: center;
|
|
1079
|
+
justify-content: center;
|
|
1080
|
+
background: {{BG_GRADIENT}};
|
|
1081
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Roboto, sans-serif;
|
|
1082
|
+
-webkit-font-smoothing: antialiased;
|
|
1083
|
+
}
|
|
1084
|
+
.card {
|
|
1085
|
+
background: transparent;
|
|
1086
|
+
border-radius: 20px;
|
|
1087
|
+
padding: 48px 56px;
|
|
1088
|
+
text-align: center;
|
|
1089
|
+
max-width: 480px;
|
|
1090
|
+
}
|
|
1091
|
+
.icon {
|
|
1092
|
+
display: flex;
|
|
1093
|
+
justify-content: center;
|
|
1094
|
+
margin-bottom: 20px;
|
|
1095
|
+
animation: bounceIn 0.6s ease-out;
|
|
1096
|
+
}
|
|
1097
|
+
.icon svg { display: block; }
|
|
1098
|
+
h1 {
|
|
1099
|
+
margin: 0 0 12px;
|
|
1100
|
+
font-size: 26px;
|
|
1101
|
+
font-weight: 600;
|
|
1102
|
+
color: #fff;
|
|
1103
|
+
letter-spacing: 0.02em;
|
|
1104
|
+
}
|
|
1105
|
+
p {
|
|
1106
|
+
margin: 0;
|
|
1107
|
+
font-size: 15px;
|
|
1108
|
+
line-height: 1.6;
|
|
1109
|
+
color: rgba(255, 255, 255, 0.88);
|
|
1110
|
+
}
|
|
1111
|
+
@keyframes bounceIn {
|
|
1112
|
+
0% { transform: scale(0); opacity: 0; }
|
|
1113
|
+
50% { transform: scale(1.15); }
|
|
1114
|
+
100% { transform: scale(1); opacity: 1; }
|
|
1115
|
+
}
|
|
1116
|
+
</style>
|
|
1117
|
+
</head>
|
|
1118
|
+
<body>
|
|
1119
|
+
<div class="card">
|
|
1120
|
+
<div class="icon">{{ICON}}</div>
|
|
1121
|
+
<h1>{{TITLE}}</h1>
|
|
1122
|
+
<p>{{MESSAGE}}</p>
|
|
1123
|
+
</div>
|
|
1124
|
+
</body>
|
|
1125
|
+
</html>`;
|
|
1126
|
+
function escapeHtml(value) {
|
|
1127
|
+
return value.replace(/[&<>"']/g, (ch) => {
|
|
1128
|
+
switch (ch) {
|
|
1129
|
+
case "&":
|
|
1130
|
+
return "&";
|
|
1131
|
+
case "<":
|
|
1132
|
+
return "<";
|
|
1133
|
+
case ">":
|
|
1134
|
+
return ">";
|
|
1135
|
+
case '"':
|
|
1136
|
+
return """;
|
|
1137
|
+
case "'":
|
|
1138
|
+
return "'";
|
|
1139
|
+
default:
|
|
1140
|
+
return ch;
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
function renderLoginPage(kind, options) {
|
|
1145
|
+
const vars = PAGES[kind];
|
|
1146
|
+
const message = options?.message?.trim() ? options.message : vars.message;
|
|
1147
|
+
return TEMPLATE.replace(/\{\{ICON\}\}/g, vars.icon).replace(/\{\{TITLE\}\}/g, escapeHtml(vars.title)).replace(/\{\{MESSAGE\}\}/g, escapeHtml(message)).replace(/\{\{BG_GRADIENT\}\}/g, vars.bgGradient);
|
|
1148
|
+
}
|
|
1149
|
+
|
|
546
1150
|
// src/core/auth-mgr.ts
|
|
547
|
-
import * as
|
|
1151
|
+
import * as crypto3 from "crypto";
|
|
548
1152
|
import * as http from "http";
|
|
549
|
-
import {
|
|
550
|
-
import
|
|
551
|
-
import path3 from "path";
|
|
552
|
-
import os2 from "os";
|
|
1153
|
+
import { execFile } from "child_process";
|
|
1154
|
+
import fs5 from "fs";
|
|
553
1155
|
var DEVECO_CACHE_TTL_MS = 30 * 60 * 1e3;
|
|
1156
|
+
var OAUTH_EXPIRY_SKEW_MS = 5 * 60 * 1e3;
|
|
1157
|
+
function oauthAccessDecision(cache, now = Date.now(), skewMs = OAUTH_EXPIRY_SKEW_MS) {
|
|
1158
|
+
if (!cache?.accessToken) return "relogin";
|
|
1159
|
+
const expiresAt = cache.expiresAt;
|
|
1160
|
+
const hasExpiry = typeof expiresAt === "number" && Number.isFinite(expiresAt) && expiresAt > 0;
|
|
1161
|
+
if (!hasExpiry) return "use";
|
|
1162
|
+
if (expiresAt > now + skewMs) return "use";
|
|
1163
|
+
if (cache.refreshToken) return "refresh";
|
|
1164
|
+
return "relogin";
|
|
1165
|
+
}
|
|
1166
|
+
function resolveExpiresAt(expireTime, previousExpiresAt, now = Date.now()) {
|
|
1167
|
+
if (Number.isFinite(expireTime) && expireTime > 0) return now + expireTime * 1e3;
|
|
1168
|
+
if (typeof previousExpiresAt === "number" && Number.isFinite(previousExpiresAt) && previousExpiresAt > now + OAUTH_EXPIRY_SKEW_MS) {
|
|
1169
|
+
return previousExpiresAt;
|
|
1170
|
+
}
|
|
1171
|
+
return 0;
|
|
1172
|
+
}
|
|
1173
|
+
var NOT_LOGGED_IN = "Not logged in. Run `connect-api-cli auth login` and finish authorization in the browser.";
|
|
1174
|
+
var NEED_RELOGIN = "OAuth token refresh failed, need to re-login";
|
|
1175
|
+
var HARMONY_AA_CANDIDATES = ["/bin/aa", "/system/bin/aa", "/usr/bin/aa"];
|
|
1176
|
+
function detectBrowserHost(input) {
|
|
1177
|
+
const platform = input?.platform ?? process.platform;
|
|
1178
|
+
if (platform === "win32") return "win32";
|
|
1179
|
+
if (platform === "darwin") return "darwin";
|
|
1180
|
+
const osRelease = input?.osRelease ?? readOsRelease();
|
|
1181
|
+
const hasAa = input?.hasAa ?? harmonyAaExists();
|
|
1182
|
+
if (/harmonyos|openharmony/i.test(osRelease) || hasAa) return "harmony";
|
|
1183
|
+
return "linux";
|
|
1184
|
+
}
|
|
1185
|
+
function browserLaunchSpec(url, host = detectBrowserHost()) {
|
|
1186
|
+
if (host === "win32") {
|
|
1187
|
+
return { file: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
|
|
1188
|
+
}
|
|
1189
|
+
if (host === "darwin") {
|
|
1190
|
+
return { file: "open", args: [url] };
|
|
1191
|
+
}
|
|
1192
|
+
if (host === "harmony") {
|
|
1193
|
+
return { file: "aa", args: ["start", "-A", "ohos.want.action.viewData", "-U", url] };
|
|
1194
|
+
}
|
|
1195
|
+
return { file: "xdg-open", args: [url] };
|
|
1196
|
+
}
|
|
554
1197
|
var AuthManager = class {
|
|
555
|
-
|
|
1198
|
+
/** 并发的 OAuth 登录共用同一次浏览器授权。 */
|
|
556
1199
|
static pendingOAuthLogin;
|
|
1200
|
+
/** 并发请求共用一次刷新,避免同时打刷新接口或互相清缓存。 */
|
|
1201
|
+
static oauthRefreshInFlight = null;
|
|
557
1202
|
/**
|
|
558
1203
|
* 获取当前生效的 access token,并具备自动刷新能力:
|
|
559
|
-
* - OAuth
|
|
1204
|
+
* - OAuth:未过期,或没有过期时间时,直接用缓存。过期且有 refreshToken 才刷新。
|
|
1205
|
+
* 请求路径不打开浏览器;需要重新授权时抛错,由 `auth login` 或 DevEco 降级处理。
|
|
560
1206
|
* - client_credentials / service_account:过期后重新换取 / 重新签 JWT
|
|
561
1207
|
* - deveco:过期后重新解密本地登录态并 refresh 换取
|
|
562
1208
|
*
|
|
563
|
-
* force 跳过缓存(供
|
|
1209
|
+
* force 跳过缓存(供 401 重试使用)。OAuth 在 force 时只走 refreshToken。
|
|
564
1210
|
*/
|
|
565
1211
|
static async getAccessToken(force = false) {
|
|
566
1212
|
const { config: config2, cache } = this.getStatus();
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
if (!force && cache && cache.expiresAt > Date.now() +
|
|
1213
|
+
if (config2.authMode === "oauth") {
|
|
1214
|
+
return this.getOAuthAccessToken(config2, cache, force, false);
|
|
1215
|
+
}
|
|
1216
|
+
if (!force && cache && cache.expiresAt > Date.now() + OAUTH_EXPIRY_SKEW_MS) {
|
|
571
1217
|
return cache.accessToken;
|
|
572
1218
|
}
|
|
573
|
-
|
|
1219
|
+
return this.acquire(config2);
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* interactive 为真时,缓存不可用会打开浏览器。
|
|
1223
|
+
* 请求路径(interactive 为假)只使用或刷新已有 token,不会占用 12306。
|
|
1224
|
+
*/
|
|
1225
|
+
static async getOAuthAccessToken(cfg, cache, force, interactive) {
|
|
1226
|
+
if (!force) {
|
|
1227
|
+
const decision = oauthAccessDecision(cache);
|
|
1228
|
+
if (decision === "use") return cache.accessToken;
|
|
1229
|
+
if (decision === "refresh") {
|
|
1230
|
+
try {
|
|
1231
|
+
return await this.refreshCachedOAuth(cfg, cache);
|
|
1232
|
+
} catch (e) {
|
|
1233
|
+
if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache?.accessToken) {
|
|
1234
|
+
return cache.accessToken;
|
|
1235
|
+
}
|
|
1236
|
+
if (!interactive) throw e;
|
|
1237
|
+
}
|
|
1238
|
+
} else if (!interactive) {
|
|
1239
|
+
throw new Error(NOT_LOGGED_IN);
|
|
1240
|
+
}
|
|
1241
|
+
} else if (cache?.refreshToken) {
|
|
574
1242
|
try {
|
|
575
|
-
|
|
576
|
-
const expiresAt = Date.now() + refreshed.expireTime * 1e3;
|
|
577
|
-
this.writeCache({
|
|
578
|
-
accessToken: refreshed.accessToken,
|
|
579
|
-
expiresAt,
|
|
580
|
-
clientId: cfg.clientId,
|
|
581
|
-
domain: cfg.domain,
|
|
582
|
-
authMode: cfg.authMode,
|
|
583
|
-
refreshToken: cache.refreshToken
|
|
584
|
-
// 刷新接口不返回新 refreshToken,沿用旧值
|
|
585
|
-
});
|
|
586
|
-
return refreshed.accessToken;
|
|
1243
|
+
return await this.refreshCachedOAuth(cfg, cache);
|
|
587
1244
|
} catch (e) {
|
|
588
|
-
|
|
589
|
-
|
|
1245
|
+
if (!(e instanceof Error && e.message === NEED_RELOGIN) && cache.accessToken && !interactive) {
|
|
1246
|
+
return cache.accessToken;
|
|
1247
|
+
}
|
|
1248
|
+
if (!interactive) throw e;
|
|
590
1249
|
}
|
|
1250
|
+
} else if (!interactive) {
|
|
1251
|
+
throw new Error(NOT_LOGGED_IN);
|
|
591
1252
|
}
|
|
592
|
-
|
|
1253
|
+
this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
|
|
1254
|
+
this.pendingOAuthLogin = void 0;
|
|
1255
|
+
});
|
|
1256
|
+
return this.pendingOAuthLogin;
|
|
593
1257
|
}
|
|
594
1258
|
/** 登录入口:按当前认证模式获取并缓存 token */
|
|
595
1259
|
static async login() {
|
|
@@ -599,10 +1263,8 @@ var AuthManager = class {
|
|
|
599
1263
|
/** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
|
|
600
1264
|
static async acquire(cfg) {
|
|
601
1265
|
if (cfg.authMode === "oauth") {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
});
|
|
605
|
-
return this.pendingOAuthLogin;
|
|
1266
|
+
const cache = this.matchingCache(cfg, this.readCache());
|
|
1267
|
+
return this.getOAuthAccessToken(cfg, cache, false, true);
|
|
606
1268
|
}
|
|
607
1269
|
if (cfg.authMode === "deveco") {
|
|
608
1270
|
try {
|
|
@@ -612,7 +1274,7 @@ var AuthManager = class {
|
|
|
612
1274
|
const oauthConfig = getConfig("oauth");
|
|
613
1275
|
const cache = this.matchingCache(oauthConfig, this.readCache());
|
|
614
1276
|
console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
|
|
615
|
-
return this.
|
|
1277
|
+
return this.getOAuthAccessToken(oauthConfig, cache, false, true);
|
|
616
1278
|
}
|
|
617
1279
|
}
|
|
618
1280
|
if (cfg.authMode === "service_account") {
|
|
@@ -643,51 +1305,68 @@ var AuthManager = class {
|
|
|
643
1305
|
}
|
|
644
1306
|
throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
|
|
645
1307
|
}
|
|
646
|
-
/** OAuth 授权码登录:启动本地回调服务器 +
|
|
1308
|
+
/** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器。同一进程只开一次。 */
|
|
647
1309
|
static loginOAuth(cfg) {
|
|
648
1310
|
return new Promise((resolve2, reject) => {
|
|
649
1311
|
const redirectUri = cfg.oauth.redirectUri;
|
|
650
1312
|
const port = Number(new URL(redirectUri).port || 80);
|
|
651
|
-
const state =
|
|
652
|
-
|
|
1313
|
+
const state = crypto3.randomBytes(32).toString("hex");
|
|
1314
|
+
let settled = false;
|
|
1315
|
+
let server;
|
|
1316
|
+
const finish = (err, token) => {
|
|
1317
|
+
if (settled) return;
|
|
1318
|
+
settled = true;
|
|
1319
|
+
server.close();
|
|
1320
|
+
if (err) reject(err);
|
|
1321
|
+
else resolve2(token);
|
|
1322
|
+
};
|
|
1323
|
+
server = http.createServer(async (req, res) => {
|
|
653
1324
|
try {
|
|
654
|
-
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
1325
|
+
const url = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
|
|
655
1326
|
const code = url.searchParams.get("code");
|
|
656
1327
|
const returnedState = url.searchParams.get("state");
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
res.
|
|
1328
|
+
const oauthError = url.searchParams.get("error");
|
|
1329
|
+
if (!code && !oauthError) {
|
|
1330
|
+
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
1331
|
+
res.end();
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
if (oauthError || !code || returnedState !== state) {
|
|
1335
|
+
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";
|
|
1336
|
+
sendLoginPage(res, "failed", detail, 400);
|
|
1337
|
+
finish(new Error(detail));
|
|
660
1338
|
return;
|
|
661
1339
|
}
|
|
662
1340
|
const token = await AuthService.getOAuthToken(code, redirectUri);
|
|
663
|
-
const expiresAt = Date.now() + token.expireTime * 1e3;
|
|
664
1341
|
clearOAuthTeamIdCache();
|
|
665
1342
|
this.writeCache({
|
|
666
1343
|
accessToken: token.accessToken,
|
|
667
|
-
expiresAt,
|
|
1344
|
+
expiresAt: resolveExpiresAt(token.expireTime),
|
|
668
1345
|
clientId: cfg.clientId,
|
|
669
1346
|
domain: cfg.domain,
|
|
670
1347
|
authMode: cfg.authMode,
|
|
671
1348
|
refreshToken: token.refreshToken
|
|
672
1349
|
});
|
|
673
|
-
res
|
|
674
|
-
|
|
675
|
-
server.close();
|
|
676
|
-
resolve2(token.accessToken);
|
|
1350
|
+
sendLoginPage(res, "success");
|
|
1351
|
+
finish(void 0, token.accessToken);
|
|
677
1352
|
} catch (err) {
|
|
678
|
-
|
|
679
|
-
|
|
1353
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1354
|
+
if (!res.headersSent) sendLoginPage(res, "failed", message || "\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u5173\u95ED\u9875\u9762\u5E76\u91CD\u8BD5");
|
|
1355
|
+
finish(err instanceof Error ? err : new Error(message));
|
|
680
1356
|
}
|
|
681
1357
|
});
|
|
682
1358
|
server.on("error", (err) => {
|
|
683
|
-
|
|
684
|
-
|
|
1359
|
+
if (err.code === "EADDRINUSE") {
|
|
1360
|
+
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"));
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
finish(err);
|
|
685
1364
|
});
|
|
686
1365
|
server.listen(port, () => {
|
|
687
1366
|
const authUrl = AuthService.buildAuthUrl(state);
|
|
688
1367
|
console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
|
|
689
1368
|
console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
|
|
690
|
-
|
|
1369
|
+
launchBrowser(authUrl);
|
|
691
1370
|
});
|
|
692
1371
|
});
|
|
693
1372
|
}
|
|
@@ -724,50 +1403,92 @@ var AuthManager = class {
|
|
|
724
1403
|
static matchingCache(cfg, cache) {
|
|
725
1404
|
return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
|
|
726
1405
|
}
|
|
727
|
-
static
|
|
1406
|
+
static refreshCachedOAuth(cfg, cache) {
|
|
1407
|
+
if (!this.oauthRefreshInFlight) {
|
|
1408
|
+
this.oauthRefreshInFlight = this.doRefreshCachedOAuth(cfg, cache).finally(() => {
|
|
1409
|
+
this.oauthRefreshInFlight = null;
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
return this.oauthRefreshInFlight;
|
|
1413
|
+
}
|
|
1414
|
+
static async doRefreshCachedOAuth(cfg, cache) {
|
|
728
1415
|
try {
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
1416
|
+
const refreshed = await AuthService.refreshOAuthToken(cache.refreshToken);
|
|
1417
|
+
const refreshToken = refreshed.refreshToken || cache.refreshToken;
|
|
1418
|
+
this.writeCache({
|
|
1419
|
+
accessToken: refreshed.accessToken,
|
|
1420
|
+
expiresAt: resolveExpiresAt(refreshed.expireTime, cache.expiresAt),
|
|
1421
|
+
clientId: cfg.clientId,
|
|
1422
|
+
domain: cfg.domain,
|
|
1423
|
+
authMode: cfg.authMode,
|
|
1424
|
+
refreshToken
|
|
1425
|
+
});
|
|
1426
|
+
return refreshed.accessToken;
|
|
733
1427
|
} catch (e) {
|
|
1428
|
+
if (isDefinitiveOAuthRefreshFailure(e)) {
|
|
1429
|
+
console.error("OAuth token refresh failed, need to re-login:", e instanceof Error ? e.message : String(e));
|
|
1430
|
+
this.clearCache();
|
|
1431
|
+
throw new Error(NEED_RELOGIN);
|
|
1432
|
+
}
|
|
1433
|
+
console.error("OAuth token refresh failed:", e instanceof Error ? e.message : String(e));
|
|
1434
|
+
throw e;
|
|
734
1435
|
}
|
|
735
|
-
|
|
1436
|
+
}
|
|
1437
|
+
static readCache() {
|
|
1438
|
+
const data = readVault(tokenFilePath());
|
|
1439
|
+
if (!data || typeof data !== "object") return null;
|
|
1440
|
+
const cache = data;
|
|
1441
|
+
return typeof cache.accessToken === "string" ? cache : null;
|
|
736
1442
|
}
|
|
737
1443
|
static writeCache(cache) {
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
1444
|
+
const prev = this.readCache();
|
|
1445
|
+
const sameIdentity = !!prev && prev.clientId === cache.clientId && prev.domain === cache.domain && prev.authMode === cache.authMode;
|
|
1446
|
+
const next = { ...sameIdentity ? prev : {}, ...cache };
|
|
1447
|
+
if (cache.teamId === void 0 && sameIdentity && prev?.teamId) next.teamId = prev.teamId;
|
|
1448
|
+
if (Object.prototype.hasOwnProperty.call(cache, "refreshToken") && !cache.refreshToken) {
|
|
1449
|
+
delete next.refreshToken;
|
|
741
1450
|
}
|
|
1451
|
+
writeVault(tokenFilePath(), next);
|
|
742
1452
|
}
|
|
743
1453
|
/**
|
|
744
1454
|
* 清除缓存的 Token(登出)
|
|
745
1455
|
*/
|
|
746
1456
|
static clearCache() {
|
|
747
1457
|
clearOAuthTeamIdCache();
|
|
748
|
-
|
|
749
|
-
if (fs4.existsSync(this.cacheFile)) {
|
|
750
|
-
fs4.unlinkSync(this.cacheFile);
|
|
751
|
-
return true;
|
|
752
|
-
}
|
|
753
|
-
return false;
|
|
754
|
-
} catch (e) {
|
|
755
|
-
return false;
|
|
756
|
-
}
|
|
1458
|
+
return clearVault(tokenFilePath());
|
|
757
1459
|
}
|
|
758
1460
|
};
|
|
759
|
-
function
|
|
760
|
-
const
|
|
761
|
-
|
|
762
|
-
|
|
1461
|
+
function sendLoginPage(res, kind, message, status = 200) {
|
|
1462
|
+
const html = renderLoginPage(kind, message ? { message } : void 0);
|
|
1463
|
+
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
|
|
1464
|
+
res.end(html);
|
|
1465
|
+
}
|
|
1466
|
+
function launchBrowser(url) {
|
|
1467
|
+
const host = detectBrowserHost();
|
|
1468
|
+
const spec = browserLaunchSpec(url, host);
|
|
1469
|
+
if (host === "harmony") spec.file = resolveHarmonyAa();
|
|
1470
|
+
execFile(spec.file, spec.args, { windowsHide: true }, (err) => {
|
|
763
1471
|
if (err) {
|
|
764
1472
|
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");
|
|
765
1473
|
}
|
|
766
1474
|
});
|
|
767
1475
|
}
|
|
1476
|
+
function readOsRelease() {
|
|
1477
|
+
try {
|
|
1478
|
+
if (fs5.existsSync("/etc/os-release")) return fs5.readFileSync("/etc/os-release", "utf8");
|
|
1479
|
+
} catch {
|
|
1480
|
+
}
|
|
1481
|
+
return "";
|
|
1482
|
+
}
|
|
1483
|
+
function harmonyAaExists() {
|
|
1484
|
+
return HARMONY_AA_CANDIDATES.some((file) => fs5.existsSync(file));
|
|
1485
|
+
}
|
|
1486
|
+
function resolveHarmonyAa() {
|
|
1487
|
+
return HARMONY_AA_CANDIDATES.find((file) => fs5.existsSync(file)) ?? "aa";
|
|
1488
|
+
}
|
|
768
1489
|
|
|
769
1490
|
// src/core/request-source.ts
|
|
770
|
-
import
|
|
1491
|
+
import fs6 from "fs";
|
|
771
1492
|
import path4 from "path";
|
|
772
1493
|
var REQUEST_SOURCE_HEADER = "Request-Source";
|
|
773
1494
|
var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
|
|
@@ -908,7 +1629,7 @@ function getRequestSource() {
|
|
|
908
1629
|
return agent ? `${agent}-skill` : SKILL_CHANNEL;
|
|
909
1630
|
}
|
|
910
1631
|
function readVersion() {
|
|
911
|
-
const fromBuild = injected(true ? "1.1.
|
|
1632
|
+
const fromBuild = injected(true ? "1.1.11" : void 0);
|
|
912
1633
|
if (fromBuild) return fromBuild;
|
|
913
1634
|
const candidates = [
|
|
914
1635
|
path4.join(__dirname, "..", "..", "package.json"),
|
|
@@ -916,7 +1637,7 @@ function readVersion() {
|
|
|
916
1637
|
];
|
|
917
1638
|
for (const pkgPath of candidates) {
|
|
918
1639
|
try {
|
|
919
|
-
const pkg = JSON.parse(
|
|
1640
|
+
const pkg = JSON.parse(fs6.readFileSync(pkgPath, "utf8"));
|
|
920
1641
|
if (pkg.version) return pkg.version;
|
|
921
1642
|
} catch {
|
|
922
1643
|
}
|
|
@@ -1010,7 +1731,7 @@ connectApiClient.interceptors.response.use(
|
|
|
1010
1731
|
original._retry = true;
|
|
1011
1732
|
try {
|
|
1012
1733
|
const cfg = getConfig();
|
|
1013
|
-
const newToken = await AuthManager.getAccessToken(
|
|
1734
|
+
const newToken = await AuthManager.getAccessToken(true);
|
|
1014
1735
|
if (!original.headers) {
|
|
1015
1736
|
original.headers = {};
|
|
1016
1737
|
}
|
|
@@ -1018,6 +1739,10 @@ connectApiClient.interceptors.response.use(
|
|
|
1018
1739
|
if (original._autoTeamId) deleteHeader(original.headers, "teamId");
|
|
1019
1740
|
return connectApiClient(original);
|
|
1020
1741
|
} catch (e) {
|
|
1742
|
+
if (e instanceof Error && e.message) {
|
|
1743
|
+
err.message = `${err.message}
|
|
1744
|
+
${e.message}`;
|
|
1745
|
+
}
|
|
1021
1746
|
return Promise.reject(err);
|
|
1022
1747
|
}
|
|
1023
1748
|
}
|
|
@@ -1371,7 +2096,7 @@ var ProjectService = class {
|
|
|
1371
2096
|
|
|
1372
2097
|
// src/services/upload.ts
|
|
1373
2098
|
import axios4 from "axios";
|
|
1374
|
-
import
|
|
2099
|
+
import fs7 from "fs";
|
|
1375
2100
|
import path5 from "path";
|
|
1376
2101
|
function pickObjectId(res) {
|
|
1377
2102
|
return res.urlInfo?.objectId || res.objectId;
|
|
@@ -1411,7 +2136,7 @@ var UploadService = class {
|
|
|
1411
2136
|
* 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
|
|
1412
2137
|
*/
|
|
1413
2138
|
static async uploadFile(options) {
|
|
1414
|
-
const stat =
|
|
2139
|
+
const stat = fs7.statSync(options.filePath);
|
|
1415
2140
|
const fileName = path5.basename(options.filePath) || "unknown";
|
|
1416
2141
|
if (stat.size < 5 * 1024 * 1024) {
|
|
1417
2142
|
return this.uploadSingleFile(options, fileName, stat.size);
|
|
@@ -1453,7 +2178,7 @@ var UploadService = class {
|
|
|
1453
2178
|
);
|
|
1454
2179
|
}
|
|
1455
2180
|
const { url, headers } = urlRes.urlInfo;
|
|
1456
|
-
const fileStream =
|
|
2181
|
+
const fileStream = fs7.createReadStream(options.filePath);
|
|
1457
2182
|
await axios4.put(url, fileStream, {
|
|
1458
2183
|
headers: this.buildObsPutHeaders(headers, contentLength),
|
|
1459
2184
|
maxBodyLength: Infinity,
|
|
@@ -1494,7 +2219,7 @@ var UploadService = class {
|
|
|
1494
2219
|
if (!uploadInfoMap) {
|
|
1495
2220
|
throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
|
|
1496
2221
|
}
|
|
1497
|
-
const fd =
|
|
2222
|
+
const fd = fs7.openSync(options.filePath, "r");
|
|
1498
2223
|
const composeReqBody = {};
|
|
1499
2224
|
for (let i = 1; i <= partsCount; i++) {
|
|
1500
2225
|
const propKey = `additionalProp${i}`;
|
|
@@ -1503,7 +2228,7 @@ var UploadService = class {
|
|
|
1503
2228
|
const end = Math.min(start + partSize, fileSize);
|
|
1504
2229
|
const length = end - start;
|
|
1505
2230
|
const buffer = Buffer.alloc(length);
|
|
1506
|
-
|
|
2231
|
+
fs7.readSync(fd, buffer, 0, length, start);
|
|
1507
2232
|
const res = await axios4.put(uploadInfo.url, buffer, {
|
|
1508
2233
|
headers: this.buildObsPutHeaders(uploadInfo.headers, length),
|
|
1509
2234
|
maxBodyLength: Infinity,
|
|
@@ -1515,7 +2240,7 @@ var UploadService = class {
|
|
|
1515
2240
|
etag
|
|
1516
2241
|
};
|
|
1517
2242
|
}
|
|
1518
|
-
|
|
2243
|
+
fs7.closeSync(fd);
|
|
1519
2244
|
await this.composeMultipart({
|
|
1520
2245
|
objectId,
|
|
1521
2246
|
nspUploadId,
|
|
@@ -1645,10 +2370,13 @@ var ProvisionService = class {
|
|
|
1645
2370
|
};
|
|
1646
2371
|
export {
|
|
1647
2372
|
AuthService,
|
|
2373
|
+
OAuthRefreshRejectedError,
|
|
1648
2374
|
ProjectService,
|
|
1649
2375
|
ProvisionService,
|
|
1650
2376
|
PublishService,
|
|
1651
2377
|
UploadService,
|
|
1652
2378
|
connectApiClient,
|
|
1653
|
-
getConfig
|
|
2379
|
+
getConfig,
|
|
2380
|
+
isDefinitiveOAuthRefreshFailure,
|
|
2381
|
+
normalizeOAuthToken
|
|
1654
2382
|
};
|