dsh-codearts 1.2.14 → 1.3.0
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/CHANGELOG.md +44 -0
- package/lib/auth-CF9XHMX-.mjs +1008 -0
- package/lib/bin.mjs +3 -1
- package/lib/client/index.d.cts +15 -0
- package/lib/client/index.js +292 -116
- package/lib/index.d.mts +52 -1
- package/lib/index.mjs +381 -65
- package/lib/keeper-P4FkDUEd.mjs +215 -0
- package/lib/keeper-main.d.mts +1 -0
- package/lib/keeper-main.mjs +199 -0
- package/lib/{version-Msk-1m2n.mjs → upstream-CVtspzAv.mjs} +2 -1469
- package/lib/version-CJTTrulR.mjs +539 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1008 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, createSign, generateKeyPairSync, randomBytes } from "node:crypto";
|
|
2
|
+
import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import http from "node:http";
|
|
6
|
+
//#region src/dpop.ts
|
|
7
|
+
/**
|
|
8
|
+
* DPoP(RFC 9449)证明 JWT:ES256 + P-256,供 oauth2/tokens 请求头使用。
|
|
9
|
+
* 翻译自 codearts2api 的 internal/upstream/dpop.go。
|
|
10
|
+
*
|
|
11
|
+
* 关键约束:refresh_token 与首次换取时的 DPoP 公钥绑定,刷新时必须复用同一
|
|
12
|
+
* 私钥,否则 STS 报 InvalidDPoPHeader。因此该私钥必须随 refresh_token 一起落盘。
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-codearts/dpop
|
|
15
|
+
*/
|
|
16
|
+
const P256_ORDER = BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
|
|
17
|
+
const P256_HALF = P256_ORDER >> 1n;
|
|
18
|
+
/** 生成新的 DPoP 私钥(JWK)。 */
|
|
19
|
+
function newDPoPPrivateJWK() {
|
|
20
|
+
const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
21
|
+
const jwk = privateKey.export({ format: "jwk" });
|
|
22
|
+
return {
|
|
23
|
+
kty: jwk.kty,
|
|
24
|
+
crv: jwk.crv,
|
|
25
|
+
x: jwk.x,
|
|
26
|
+
y: jwk.y,
|
|
27
|
+
d: jwk.d
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function privateKeyFromJWK(jwk) {
|
|
31
|
+
return createPrivateKey({
|
|
32
|
+
key: jwk,
|
|
33
|
+
format: "jwk"
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function b64u(buf) {
|
|
37
|
+
return Buffer.from(buf).toString("base64url");
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 生成 DPoP proof JWT(htm=POST,htu=token 端点)。
|
|
41
|
+
* 低 S 归一化以兼容服务端校验。
|
|
42
|
+
*/
|
|
43
|
+
function signDpopProof(jwk, htu) {
|
|
44
|
+
const key = privateKeyFromJWK(jwk);
|
|
45
|
+
const header = {
|
|
46
|
+
alg: "ES256",
|
|
47
|
+
typ: "dpop+jwt",
|
|
48
|
+
jwk: {
|
|
49
|
+
kty: "EC",
|
|
50
|
+
crv: "P-256",
|
|
51
|
+
x: jwk.x,
|
|
52
|
+
y: jwk.y
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const headerJSON = Buffer.from(JSON.stringify(header));
|
|
56
|
+
const payload = {
|
|
57
|
+
htm: "POST",
|
|
58
|
+
htu,
|
|
59
|
+
iat: Math.floor(Date.now() / 1e3),
|
|
60
|
+
jti: randomBytes(16).toString("hex")
|
|
61
|
+
};
|
|
62
|
+
const payloadJSON = Buffer.from(JSON.stringify(payload));
|
|
63
|
+
const input = `${b64u(headerJSON)}.${b64u(payloadJSON)}`;
|
|
64
|
+
const sig = createSign("SHA256").update(input).sign({
|
|
65
|
+
key,
|
|
66
|
+
dsaEncoding: "ieee-p1363"
|
|
67
|
+
});
|
|
68
|
+
let s = sig.subarray(32, 64);
|
|
69
|
+
let sBig = BigInt(`0x${s.toString("hex")}`);
|
|
70
|
+
if (sBig > P256_HALF) {
|
|
71
|
+
sBig = P256_ORDER - sBig;
|
|
72
|
+
s = Buffer.from(sBig.toString(16).padStart(64, "0"), "hex");
|
|
73
|
+
}
|
|
74
|
+
return `${input}.${b64u(Buffer.concat([sig.subarray(0, 32), s]))}`;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/oauth.ts
|
|
78
|
+
/**
|
|
79
|
+
* CodeArts OAuth2(PKCE)登录 + 刷新,翻译自 codearts2api 的
|
|
80
|
+
* internal/server/oauth.go / cmd/login/main.go / internal/upstream/client.go。
|
|
81
|
+
*
|
|
82
|
+
* 登录:本地起 127.0.0.1 回调服务 → 浏览器跳 codearts.huaweicloud.com/authorize
|
|
83
|
+
* → 用户登录 → 华为回调带 code → 用 code + PKCE verifier + DPoP 私钥换
|
|
84
|
+
* security_token + 临时 AK/SK + refresh_token。
|
|
85
|
+
*
|
|
86
|
+
* 刷新:refresh_token 与 client_id、DPoP 私钥三者绑定,刷新时原样复用。
|
|
87
|
+
*
|
|
88
|
+
* @module dsh-codearts/oauth
|
|
89
|
+
*/
|
|
90
|
+
const CLIENT_ID = "codearts-agent";
|
|
91
|
+
const PLUGIN_NAME = "snap_AIIDE";
|
|
92
|
+
const PLUGIN_VERSION = "5.2.0";
|
|
93
|
+
const SNAP_HOST = "https://snap-access.cn-north-4.myhuaweicloud.com";
|
|
94
|
+
const STS_HOST = "https://sts.cn-north-4.myhuaweicloud.com";
|
|
95
|
+
const PORTAL = "https://codearts.huaweicloud.com/portal";
|
|
96
|
+
const REDIRECT_PATH = "/oauth/callback";
|
|
97
|
+
function defaultLoginConfig() {
|
|
98
|
+
return {
|
|
99
|
+
clientId: CLIENT_ID,
|
|
100
|
+
snapHost: SNAP_HOST,
|
|
101
|
+
stsHost: STS_HOST,
|
|
102
|
+
portal: PORTAL
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function randomHex(n) {
|
|
106
|
+
return randomBytes(n).toString("hex");
|
|
107
|
+
}
|
|
108
|
+
function pkce() {
|
|
109
|
+
const verifier = base64url(randomBytes(64));
|
|
110
|
+
return {
|
|
111
|
+
verifier,
|
|
112
|
+
challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
113
|
+
method: "S256"
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function base64url(buf) {
|
|
117
|
+
return buf.toString("base64url");
|
|
118
|
+
}
|
|
119
|
+
/** 构造华为授权页 URL(浏览器打开,用户登录后回调本机)。 */
|
|
120
|
+
function buildAuthorizeURL(cfg, ticketId, challenge, method, port) {
|
|
121
|
+
const q = new URLSearchParams();
|
|
122
|
+
q.set("theme", "2");
|
|
123
|
+
q.set("locale", "zh-cn");
|
|
124
|
+
q.set("uri_scheme", cfg.clientId);
|
|
125
|
+
q.set("client_id", cfg.clientId);
|
|
126
|
+
q.set("port", String(port));
|
|
127
|
+
q.set("code_challenge", challenge);
|
|
128
|
+
q.set("code_challenge_method", "SHA-256");
|
|
129
|
+
q.set("ticket_id", ticketId);
|
|
130
|
+
q.set("plugin-name", PLUGIN_NAME);
|
|
131
|
+
q.set("plugin-version", PLUGIN_VERSION);
|
|
132
|
+
return `${cfg.portal}/authorize?${q.toString()}`;
|
|
133
|
+
}
|
|
134
|
+
/** 换 token 请求体:application/x-www-form-urlencoded(与华为 STS 一致)。 */
|
|
135
|
+
function buildTokenBody(cfg, params) {
|
|
136
|
+
return new URLSearchParams({
|
|
137
|
+
client_id: cfg.clientId,
|
|
138
|
+
...params
|
|
139
|
+
}).toString();
|
|
140
|
+
}
|
|
141
|
+
/** 用授权 code 换 token。 */
|
|
142
|
+
async function exchangeCode(cfg, code, verifier, port, dpopJWK, abort) {
|
|
143
|
+
const htu = `${cfg.stsHost}/v1/oauth2/tokens`;
|
|
144
|
+
const dpop = signDpopProof(dpopJWK, htu);
|
|
145
|
+
const body = buildTokenBody(cfg, {
|
|
146
|
+
code,
|
|
147
|
+
code_verifier: verifier,
|
|
148
|
+
grant_type: "authorization_code",
|
|
149
|
+
redirect_uri: `http://127.0.0.1:${port}${REDIRECT_PATH}`
|
|
150
|
+
});
|
|
151
|
+
const res = await fetch(`${htu}`, {
|
|
152
|
+
method: "POST",
|
|
153
|
+
headers: {
|
|
154
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
155
|
+
"DPoP": dpop,
|
|
156
|
+
"plugin-name": PLUGIN_NAME,
|
|
157
|
+
"plugin-version": PLUGIN_VERSION
|
|
158
|
+
},
|
|
159
|
+
body,
|
|
160
|
+
signal: abort
|
|
161
|
+
});
|
|
162
|
+
if (!res.ok) {
|
|
163
|
+
const text = await res.text();
|
|
164
|
+
throw new Error(`exchange code failed: ${res.status} ${text}`);
|
|
165
|
+
}
|
|
166
|
+
return parseToken(await res.json(), dpopJWK, cfg.clientId);
|
|
167
|
+
}
|
|
168
|
+
/** 用 refresh_token 续期。 */
|
|
169
|
+
async function refreshToken(cfg, prev, abort) {
|
|
170
|
+
const htu = `${cfg.stsHost}/v1/oauth2/tokens`;
|
|
171
|
+
const dpop = signDpopProof(prev.dpopPrivateKey, htu);
|
|
172
|
+
const body = buildTokenBody(cfg, {
|
|
173
|
+
grant_type: "refresh_token",
|
|
174
|
+
refresh_token: prev.refreshToken
|
|
175
|
+
});
|
|
176
|
+
const res = await fetch(`${htu}`, {
|
|
177
|
+
method: "POST",
|
|
178
|
+
headers: {
|
|
179
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
180
|
+
"DPoP": dpop,
|
|
181
|
+
"plugin-name": PLUGIN_NAME,
|
|
182
|
+
"plugin-version": PLUGIN_VERSION
|
|
183
|
+
},
|
|
184
|
+
body,
|
|
185
|
+
signal: abort
|
|
186
|
+
});
|
|
187
|
+
if (!res.ok) {
|
|
188
|
+
const text = await res.text();
|
|
189
|
+
throw new Error(`refresh token failed: ${res.status} ${text}`);
|
|
190
|
+
}
|
|
191
|
+
return parseToken(await res.json(), prev.dpopPrivateKey, prev.clientId, prev);
|
|
192
|
+
}
|
|
193
|
+
function parseToken(json, dpopJWK, clientId, prev) {
|
|
194
|
+
const cred = json.credentials ?? {};
|
|
195
|
+
return {
|
|
196
|
+
userId: json.user_id ?? prev?.userId ?? "",
|
|
197
|
+
userName: json.user_name ?? prev?.userName ?? "",
|
|
198
|
+
domainId: json.domain_id ?? prev?.domainId ?? "",
|
|
199
|
+
securityToken: cred.security_token ?? cred.SecurityToken ?? "",
|
|
200
|
+
accessKeyId: cred.access_key_id ?? cred.AccessKeyID ?? "",
|
|
201
|
+
secretAccessKey: cred.secret_access_key ?? cred.SecretAccessKey ?? "",
|
|
202
|
+
expiration: cred.expiration ?? cred.Expiration ?? "",
|
|
203
|
+
refreshToken: json.refresh_token ?? json.RefreshToken ?? prev?.refreshToken ?? "",
|
|
204
|
+
clientId,
|
|
205
|
+
dpopPrivateKey: dpopJWK
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* 华为登录后浏览器落回本机回调的落地页。
|
|
210
|
+
*
|
|
211
|
+
* 这一页本身没有任何后续逻辑:`code` 在响应发出的同一时刻就已交给等待队列
|
|
212
|
+
* (见 startLogin 里的 finish),token 交换完全在服务端做,页面关不关都不影响
|
|
213
|
+
* 登录结果。它只是 redirect_uri 必然要渲染的一个落点 —— 华为侧没有「登录成功」
|
|
214
|
+
* 页可停留,成功标志就是这一次 302 到 127.0.0.1。
|
|
215
|
+
*
|
|
216
|
+
* 卡片用 `window.open` 打开授权页,所以这个标签页能自己关掉;用户从卡片的
|
|
217
|
+
* 手动链接打开、或浏览器拦脚本关窗时 close 会失败,1.2s 后把提示换成「可关闭」。
|
|
218
|
+
*/
|
|
219
|
+
const CALLBACK_HTML = `<!doctype html>
|
|
220
|
+
<html lang="zh-CN">
|
|
221
|
+
<head>
|
|
222
|
+
<meta charset="utf-8">
|
|
223
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
224
|
+
<title>CodeArts 登录</title>
|
|
225
|
+
<style>
|
|
226
|
+
html,body{height:100%}
|
|
227
|
+
body{margin:0;display:flex;align-items:center;justify-content:center;background:#fff;color:#1f2329;
|
|
228
|
+
font:15px/1.6 system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
|
229
|
+
p{margin:0;padding:24px;text-align:center}
|
|
230
|
+
</style>
|
|
231
|
+
</head>
|
|
232
|
+
<body>
|
|
233
|
+
<p id="msg">正在返回 DeepSeek Harness…</p>
|
|
234
|
+
<script>
|
|
235
|
+
setTimeout(function () { try { window.close() } catch (e) {} }, 300)
|
|
236
|
+
setTimeout(function () {
|
|
237
|
+
var el = document.getElementById('msg')
|
|
238
|
+
if (el) el.textContent = 'CodeArts 登录成功,本页可关闭,请回到 DeepSeek Harness。'
|
|
239
|
+
}, 1200)
|
|
240
|
+
<\/script>
|
|
241
|
+
</body>
|
|
242
|
+
</html>`;
|
|
243
|
+
async function startLogin(cfg = defaultLoginConfig()) {
|
|
244
|
+
const ticketId = randomHex(16);
|
|
245
|
+
const { verifier, challenge, method } = pkce();
|
|
246
|
+
const dpopJWK = newDPoPPrivateJWK();
|
|
247
|
+
const codeCh = await new Promise((resolve) => {
|
|
248
|
+
const server = http.createServer();
|
|
249
|
+
const waiters = [];
|
|
250
|
+
server.on("request", (req, res) => {
|
|
251
|
+
const u = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
252
|
+
if (u.pathname !== REDIRECT_PATH) {
|
|
253
|
+
res.writeHead(404).end();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const code = u.searchParams.get("code");
|
|
257
|
+
const redirect = u.searchParams.get("redirect");
|
|
258
|
+
if (!code && redirect) {
|
|
259
|
+
res.writeHead(307, { Location: redirect }).end();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (!code) {
|
|
263
|
+
let body = "";
|
|
264
|
+
req.on("data", (c) => body += c);
|
|
265
|
+
req.on("end", () => {
|
|
266
|
+
finish(new URLSearchParams(body).get("code"));
|
|
267
|
+
});
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
finish(code);
|
|
271
|
+
function finish(c) {
|
|
272
|
+
res.writeHead(200, {
|
|
273
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
274
|
+
"Cache-Control": "no-store"
|
|
275
|
+
});
|
|
276
|
+
res.end(CALLBACK_HTML);
|
|
277
|
+
if (c) for (const w of waiters.splice(0)) w(c);
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
server.listen(0, "127.0.0.1", () => {
|
|
281
|
+
const port = server.address().port;
|
|
282
|
+
resolve({
|
|
283
|
+
port,
|
|
284
|
+
server,
|
|
285
|
+
take: () => new Promise((r) => waiters.push(r))
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
const url = buildAuthorizeURL(cfg, ticketId, challenge, method, codeCh.port);
|
|
290
|
+
const promise = (async () => {
|
|
291
|
+
const timer = setTimeout(() => codeCh.server.close(), 3e5);
|
|
292
|
+
try {
|
|
293
|
+
return await exchangeCode(cfg, await codeCh.take(), verifier, codeCh.port, dpopJWK);
|
|
294
|
+
} finally {
|
|
295
|
+
clearTimeout(timer);
|
|
296
|
+
codeCh.server.close();
|
|
297
|
+
}
|
|
298
|
+
})();
|
|
299
|
+
return {
|
|
300
|
+
url,
|
|
301
|
+
port: codeCh.port,
|
|
302
|
+
promise,
|
|
303
|
+
close: () => codeCh.server.close()
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/auth.ts
|
|
308
|
+
/**
|
|
309
|
+
* CodeArts credential store.
|
|
310
|
+
*
|
|
311
|
+
* 真实 CodeArts 桌面端聊天需要:STS `security_token` + 临时 AK/SK(HMAC 签名)
|
|
312
|
+
* + refresh_token(绑定 DPoP 私钥用于续期)。本模块持久化这全套 OAuth 凭证,
|
|
313
|
+
* 并提供自动续期。同时也保留"手动粘贴 security_token"的兜底(但无 AK/SK 时只能
|
|
314
|
+
* 作为降级态,聊天会被 APIG 拒)。
|
|
315
|
+
*
|
|
316
|
+
* @module dsh-codearts/auth
|
|
317
|
+
*/
|
|
318
|
+
/** 福利领取的上限;失败无所谓,卡住登录才是问题。 */
|
|
319
|
+
const CLAIM_TIMEOUT_MS = 15e3;
|
|
320
|
+
/** 两条凭证里较新的一条(`storedAt` 缺失视为最旧)。 */
|
|
321
|
+
function newerCredential(a, b) {
|
|
322
|
+
const at = typeof a.storedAt === "number" ? a.storedAt : 0;
|
|
323
|
+
return (typeof b.storedAt === "number" ? b.storedAt : 0) > at ? b : a;
|
|
324
|
+
}
|
|
325
|
+
/** 从 OAuthToken 落库。 */
|
|
326
|
+
function credentialFromOAuth(t, label) {
|
|
327
|
+
return {
|
|
328
|
+
token: t.securityToken,
|
|
329
|
+
accessKeyId: t.accessKeyId,
|
|
330
|
+
secretAccessKey: t.secretAccessKey,
|
|
331
|
+
refreshToken: t.refreshToken,
|
|
332
|
+
dpopPrivateKey: t.dpopPrivateKey,
|
|
333
|
+
clientId: t.clientId,
|
|
334
|
+
expiration: t.expiration,
|
|
335
|
+
userId: t.userId,
|
|
336
|
+
userName: t.userName,
|
|
337
|
+
domainId: t.domainId,
|
|
338
|
+
label: label ?? t.userName ?? t.userId,
|
|
339
|
+
storedAt: Date.now()
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function codeartsAuthPath(home) {
|
|
343
|
+
const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
|
|
344
|
+
return join(base, ".codearts-auth.json");
|
|
345
|
+
}
|
|
346
|
+
async function loadCredential(path) {
|
|
347
|
+
try {
|
|
348
|
+
const raw = await readFile(path, "utf8");
|
|
349
|
+
const parsed = JSON.parse(raw);
|
|
350
|
+
if (typeof parsed.token !== "string" || parsed.token.length === 0) return void 0;
|
|
351
|
+
return {
|
|
352
|
+
...parsed,
|
|
353
|
+
token: parsed.token
|
|
354
|
+
};
|
|
355
|
+
} catch {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** 原子写一个 JSON 文件(0600)。 */
|
|
360
|
+
async function writeJsonAtomic(path, value) {
|
|
361
|
+
await mkdir(dirname(path), { recursive: true });
|
|
362
|
+
const body = JSON.stringify(value, null, 2);
|
|
363
|
+
const tmp = `${path}.${process.pid}-${Math.random().toString(36).slice(2, 10)}.tmp`;
|
|
364
|
+
try {
|
|
365
|
+
await writeFile(tmp, body, { mode: 384 });
|
|
366
|
+
await chmod(tmp, 384).catch(() => {});
|
|
367
|
+
await rename(tmp, path);
|
|
368
|
+
} catch {
|
|
369
|
+
await unlink(tmp).catch(() => {});
|
|
370
|
+
await writeFile(path, body, { mode: 384 });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function saveCredential(path, cred) {
|
|
374
|
+
await writeJsonAtomic(path, cred);
|
|
375
|
+
}
|
|
376
|
+
async function clearCredential(path) {
|
|
377
|
+
try {
|
|
378
|
+
await unlink(path);
|
|
379
|
+
} catch {}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* 领取限时福利(幂等);无 AK/SK 时静默跳过。
|
|
383
|
+
*
|
|
384
|
+
* 必须带超时:领取失败不该拖住登录/续期。早先没传 signal,claimBenefit 的
|
|
385
|
+
* fetch 就没有任何超时 —— 福利接口一旦不响应,ensureFresh() 永远不返回,
|
|
386
|
+
* 跟着卡死的是整个聊天请求。
|
|
387
|
+
*/
|
|
388
|
+
async function claimIfPossible(cred) {
|
|
389
|
+
if (!cred.accessKeyId || !cred.secretAccessKey) return;
|
|
390
|
+
try {
|
|
391
|
+
const { claimBenefit } = await import("./upstream-CVtspzAv.mjs").then((n) => n.D);
|
|
392
|
+
await claimBenefit({
|
|
393
|
+
token: cred.token,
|
|
394
|
+
accessKeyId: cred.accessKeyId,
|
|
395
|
+
secretAccessKey: cred.secretAccessKey,
|
|
396
|
+
securityToken: cred.token
|
|
397
|
+
}, AbortSignal.timeout(CLAIM_TIMEOUT_MS));
|
|
398
|
+
} catch {}
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* 续期判定:距过期不足这个时长就去刷。
|
|
402
|
+
*
|
|
403
|
+
* 上游签发的 token 有效期是**固定的 2 小时**(实测 2026-11-10:落库 09:44:01、
|
|
404
|
+
* 过期 11:44:00),不会因为「一直在用」而顺延。所以「能连续十几天不用登录」
|
|
405
|
+
* 的前提是**总有人在过期前把它续掉**,一旦长时间没有请求进来(比如晚上关了 DSH
|
|
406
|
+
* 超过两小时),第二天必然过期 —— 表现就是「隔天就要重新登录」。
|
|
407
|
+
*
|
|
408
|
+
* 原先这里是 5 分钟,等于只在最后一刻才补救:进程稍一停顿、或者那 5 分钟里恰好
|
|
409
|
+
* 没有请求,这次续期窗口就整个错过了。放宽到 30 分钟,配合后台保活定时器
|
|
410
|
+
* (见 index.ts 的 keepAliveLoop),只要 DSH 开着就几乎不可能真的到期。
|
|
411
|
+
*/
|
|
412
|
+
const REFRESH_SKEW_MS = 18e5;
|
|
413
|
+
var CodeArtsCredentialStore = class {
|
|
414
|
+
_current;
|
|
415
|
+
_path;
|
|
416
|
+
/** 正在进行的刷新。并发请求必须共用它,不能各刷一次。 */
|
|
417
|
+
_inflight;
|
|
418
|
+
/**
|
|
419
|
+
* 凭证代际。重登/清除会推进它,让还在飞的刷新发现自己过期,
|
|
420
|
+
* 从而不把刷新结果写回去覆盖掉刚拿到的新凭证。
|
|
421
|
+
*/
|
|
422
|
+
_gen = 0;
|
|
423
|
+
/** 作废在飞的刷新;任何直接写凭证的路径都要先调它。 */
|
|
424
|
+
invalidateInflight() {
|
|
425
|
+
this._gen += 1;
|
|
426
|
+
this._inflight = void 0;
|
|
427
|
+
}
|
|
428
|
+
constructor(path) {
|
|
429
|
+
this._path = path;
|
|
430
|
+
}
|
|
431
|
+
setPath(path) {
|
|
432
|
+
this.invalidateInflight();
|
|
433
|
+
this._current = void 0;
|
|
434
|
+
this._path = path;
|
|
435
|
+
}
|
|
436
|
+
/** 给 shim 用:返回签名所需全套。 */
|
|
437
|
+
async resolve() {
|
|
438
|
+
const cred = await this.ensureFresh();
|
|
439
|
+
if (cred === void 0) return void 0;
|
|
440
|
+
return {
|
|
441
|
+
token: cred.token,
|
|
442
|
+
accessKeyId: cred.accessKeyId,
|
|
443
|
+
secretAccessKey: cred.secretAccessKey,
|
|
444
|
+
securityToken: cred.token
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
async current() {
|
|
448
|
+
return this._current ??= await loadCredential(this._path);
|
|
449
|
+
}
|
|
450
|
+
/** 从 OAuth 登录结果落库。 */
|
|
451
|
+
async setFromOAuth(t, label) {
|
|
452
|
+
this.invalidateInflight();
|
|
453
|
+
const cred = credentialFromOAuth(t, label);
|
|
454
|
+
await saveCredential(this._path, cred);
|
|
455
|
+
this._current = cred;
|
|
456
|
+
await this.claimIfPossible(cred);
|
|
457
|
+
}
|
|
458
|
+
/** 领取限时福利(幂等);无 AK/SK 时静默跳过。 */
|
|
459
|
+
async claimIfPossible(cred) {
|
|
460
|
+
await claimIfPossible(cred);
|
|
461
|
+
}
|
|
462
|
+
/** 手动粘贴 security_token(降级态,无 AK/SK)。 */
|
|
463
|
+
async set(token, label) {
|
|
464
|
+
this.invalidateInflight();
|
|
465
|
+
const cred = {
|
|
466
|
+
token: token.trim(),
|
|
467
|
+
label,
|
|
468
|
+
storedAt: Date.now()
|
|
469
|
+
};
|
|
470
|
+
await saveCredential(this._path, cred);
|
|
471
|
+
this._current = cred;
|
|
472
|
+
}
|
|
473
|
+
async clear() {
|
|
474
|
+
this.invalidateInflight();
|
|
475
|
+
this._current = void 0;
|
|
476
|
+
await clearCredential(this._path);
|
|
477
|
+
}
|
|
478
|
+
async hasCredential() {
|
|
479
|
+
return await this.current() !== void 0;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* 自动续期:若距过期不足 `REFRESH_SKEW_MS` 且具备 refresh 条件,则刷新并落库。
|
|
483
|
+
* 返回当前(可能已刷新)凭证。
|
|
484
|
+
*/
|
|
485
|
+
async ensureFresh() {
|
|
486
|
+
const gen = this._gen;
|
|
487
|
+
const cred = this._current ?? await loadCredential(this._path);
|
|
488
|
+
if (this._gen !== gen) return this._current;
|
|
489
|
+
this._current = cred;
|
|
490
|
+
if (!cred) return void 0;
|
|
491
|
+
if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
|
|
492
|
+
const exp = cred.expiration ? Date.parse(cred.expiration) : NaN;
|
|
493
|
+
if (!(Number.isNaN(exp) ? false : exp - Date.now() < REFRESH_SKEW_MS)) return cred;
|
|
494
|
+
return this._inflight ??= this.refresh(cred, {
|
|
495
|
+
refreshToken: cred.refreshToken,
|
|
496
|
+
dpopPrivateKey: cred.dpopPrivateKey,
|
|
497
|
+
clientId: cred.clientId
|
|
498
|
+
}).finally(() => {
|
|
499
|
+
this._inflight = void 0;
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
/** 真正去刷一次;失败则把凭证标成 stale 落库,让卡片提示重新登录。 */
|
|
503
|
+
async refresh(cred, mat) {
|
|
504
|
+
const gen = this._gen;
|
|
505
|
+
/**
|
|
506
|
+
* 这次刷新的结果还能不能往回写。光看代际号不够:重登是异步落库的,可能在
|
|
507
|
+
* 本次刷新启动**之后**才把 _current 换掉,那时代际号已经来不及拦。所以还要
|
|
508
|
+
* 确认「当前凭证仍然是这次刷新的那一份」。
|
|
509
|
+
*/
|
|
510
|
+
const stillCurrent = () => this._gen === gen && this._current === cred;
|
|
511
|
+
try {
|
|
512
|
+
const next = credentialFromOAuth(await refreshToken(defaultLoginConfig(), {
|
|
513
|
+
userId: cred.userId ?? "",
|
|
514
|
+
userName: cred.userName ?? "",
|
|
515
|
+
domainId: "",
|
|
516
|
+
securityToken: cred.token,
|
|
517
|
+
accessKeyId: cred.accessKeyId ?? "",
|
|
518
|
+
secretAccessKey: cred.secretAccessKey ?? "",
|
|
519
|
+
expiration: cred.expiration ?? "",
|
|
520
|
+
refreshToken: mat.refreshToken,
|
|
521
|
+
clientId: mat.clientId,
|
|
522
|
+
dpopPrivateKey: mat.dpopPrivateKey
|
|
523
|
+
}), cred.label);
|
|
524
|
+
if (!stillCurrent()) return next;
|
|
525
|
+
await saveCredential(this._path, next);
|
|
526
|
+
this._current = next;
|
|
527
|
+
await this.claimIfPossible(next);
|
|
528
|
+
return next;
|
|
529
|
+
} catch {
|
|
530
|
+
cred.stale = true;
|
|
531
|
+
if (!stillCurrent()) return cred;
|
|
532
|
+
this._current = cred;
|
|
533
|
+
try {
|
|
534
|
+
await saveCredential(this._path, cred);
|
|
535
|
+
} catch {}
|
|
536
|
+
return cred;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
/**
|
|
541
|
+
* 手工粘贴 token 的降级账号固定用这个 id:再粘一次是**覆盖**,而不是又加一个。
|
|
542
|
+
*/
|
|
543
|
+
const MANUAL_ACCOUNT_ID = "manual";
|
|
544
|
+
function codeartsAccountsPath(home) {
|
|
545
|
+
const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
|
|
546
|
+
return join(base, ".codearts-accounts.json");
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* 账号的自然键,按稳定性依次退让:
|
|
550
|
+
*
|
|
551
|
+
* 1. `userId` —— 最理想,同一个人永远同一个键。
|
|
552
|
+
* 2. `userName`。
|
|
553
|
+
* 3. **DPoP 公钥**。实测上游的 token 响应里 `user_id` / `user_name` **都是空串**
|
|
554
|
+
* (2026-09-30 用真实账号核对),所以前两级拿不到。DPoP 密钥由每次登录生成、
|
|
555
|
+
* 续期时原样复用,因此「同一次登录」内稳定、不同账号必然不同 —— 比拿 token
|
|
556
|
+
* 做键好,因为 token 每次续期都会轮换。
|
|
557
|
+
* 4. 最后才退回 token 哈希(手工粘贴的降级凭证没有 DPoP 密钥)。
|
|
558
|
+
*
|
|
559
|
+
* 已知代价:上游不给稳定身份,所以**对同一个账号重新登录**会被当成新账号,
|
|
560
|
+
* 旧条目会自己失效(凭据被拒 → 停用)并可在卡片上删掉。
|
|
561
|
+
*/
|
|
562
|
+
function accountIdOf(cred) {
|
|
563
|
+
if (typeof cred.userId === "string" && cred.userId !== "") return cred.userId;
|
|
564
|
+
if (typeof cred.userName === "string" && cred.userName !== "") return cred.userName;
|
|
565
|
+
const jwk = cred.dpopPrivateKey;
|
|
566
|
+
if (jwk !== void 0 && typeof jwk.x === "string" && typeof jwk.y === "string") return `k${createHash("sha256").update(`${jwk.x}.${jwk.y}`).digest("hex").slice(0, 15)}`;
|
|
567
|
+
return `t${createHash("sha256").update(cred.token).digest("hex").slice(0, 15)}`;
|
|
568
|
+
}
|
|
569
|
+
function summarizeAccount(id, cred) {
|
|
570
|
+
return {
|
|
571
|
+
id,
|
|
572
|
+
...cred.label === void 0 ? {} : { label: cred.label },
|
|
573
|
+
...cred.userName === void 0 ? {} : { userName: cred.userName },
|
|
574
|
+
...cred.expiration === void 0 ? {} : { expiration: cred.expiration },
|
|
575
|
+
...cred.storedAt === void 0 ? {} : { storedAt: cred.storedAt },
|
|
576
|
+
stale: cred.stale === true,
|
|
577
|
+
signable: typeof cred.accessKeyId === "string" && cred.accessKeyId !== "" && typeof cred.secretAccessKey === "string" && cred.secretAccessKey !== "",
|
|
578
|
+
paused: cred.paused === true,
|
|
579
|
+
pinned: cred.pinned === true
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* 单个账号的内存状态与续期。
|
|
584
|
+
*
|
|
585
|
+
* 每个账号一份、互不干扰。`refresh_token` 是一次性的,上游在刷新时会轮换它:
|
|
586
|
+
* 同一账号内并发刷新会烧掉它、并让失败的那次把 `stale` 盖在成功那次刚拿到的
|
|
587
|
+
* 凭证上,登录态就此写死(本机真实踩过一次)。所以这里保留单凭证时代验证过的
|
|
588
|
+
* 「单飞 + 代际」两条保护,只是作用域缩到单个账号。
|
|
589
|
+
*/
|
|
590
|
+
var AccountSlot = class {
|
|
591
|
+
_cred;
|
|
592
|
+
_inflight;
|
|
593
|
+
_gen = 0;
|
|
594
|
+
persist;
|
|
595
|
+
constructor(cred, persist) {
|
|
596
|
+
this._cred = cred;
|
|
597
|
+
this.persist = persist;
|
|
598
|
+
}
|
|
599
|
+
get credential() {
|
|
600
|
+
return this._cred;
|
|
601
|
+
}
|
|
602
|
+
/** 账号被替换或删除:作废在飞的刷新,别让它回头写回旧值。 */
|
|
603
|
+
invalidate() {
|
|
604
|
+
this._gen += 1;
|
|
605
|
+
this._inflight = void 0;
|
|
606
|
+
}
|
|
607
|
+
async ensureFresh() {
|
|
608
|
+
const cred = this._cred;
|
|
609
|
+
if (cred.stale === true) return cred;
|
|
610
|
+
if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
|
|
611
|
+
const exp = cred.expiration ? Date.parse(cred.expiration) : NaN;
|
|
612
|
+
if (!(Number.isNaN(exp) ? false : exp - Date.now() < REFRESH_SKEW_MS)) return cred;
|
|
613
|
+
return this.forceRefresh();
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* 不管还剩多久,立刻续期一次。
|
|
617
|
+
*
|
|
618
|
+
* 给上游回 `invalid_iam_token` 时用:token 可能被提前作废(另一个客户端续期、
|
|
619
|
+
* 上游轮换),而 `expiration` 还写着几小时之后,`ensureFresh` 根本不会动。
|
|
620
|
+
* 仍然走单飞,避免并发请求把一次性的 refresh_token 烧掉。
|
|
621
|
+
*/
|
|
622
|
+
async forceRefresh() {
|
|
623
|
+
const cred = this._cred;
|
|
624
|
+
if (cred.stale === true) return cred;
|
|
625
|
+
if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
|
|
626
|
+
return this._inflight ??= this.refresh(cred, {
|
|
627
|
+
refreshToken: cred.refreshToken,
|
|
628
|
+
dpopPrivateKey: cred.dpopPrivateKey,
|
|
629
|
+
clientId: cred.clientId
|
|
630
|
+
}).finally(() => {
|
|
631
|
+
this._inflight = void 0;
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
async refresh(cred, mat) {
|
|
635
|
+
const gen = this._gen;
|
|
636
|
+
const stillCurrent = () => this._gen === gen && this._cred === cred;
|
|
637
|
+
try {
|
|
638
|
+
const next = credentialFromOAuth(await refreshToken(defaultLoginConfig(), {
|
|
639
|
+
userId: cred.userId ?? "",
|
|
640
|
+
userName: cred.userName ?? "",
|
|
641
|
+
domainId: "",
|
|
642
|
+
securityToken: cred.token,
|
|
643
|
+
accessKeyId: cred.accessKeyId ?? "",
|
|
644
|
+
secretAccessKey: cred.secretAccessKey ?? "",
|
|
645
|
+
expiration: cred.expiration ?? "",
|
|
646
|
+
refreshToken: mat.refreshToken,
|
|
647
|
+
clientId: mat.clientId,
|
|
648
|
+
dpopPrivateKey: mat.dpopPrivateKey
|
|
649
|
+
}), cred.label);
|
|
650
|
+
if (!stillCurrent()) return next;
|
|
651
|
+
await this.persist(next);
|
|
652
|
+
this._cred = next;
|
|
653
|
+
await claimIfPossible(next);
|
|
654
|
+
return next;
|
|
655
|
+
} catch {
|
|
656
|
+
cred.stale = true;
|
|
657
|
+
if (!stillCurrent()) return cred;
|
|
658
|
+
this._cred = cred;
|
|
659
|
+
try {
|
|
660
|
+
await this.persist(cred);
|
|
661
|
+
} catch {}
|
|
662
|
+
return cred;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
/**
|
|
667
|
+
* 读账号文档。
|
|
668
|
+
*
|
|
669
|
+
* 导出给守护进程(`keeper-main.ts`)用:它跑在 DSH 之外的独立进程里,只做「读文档 →
|
|
670
|
+
* 续期 → 写回」这一件事,不需要 `CodeArtsAccountStore` 那套槽位/冷却/单飞状态。
|
|
671
|
+
*/
|
|
672
|
+
async function readAccountDocument(path) {
|
|
673
|
+
try {
|
|
674
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
675
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
676
|
+
const accounts = parsed.accounts ?? {};
|
|
677
|
+
const order = Array.isArray(parsed.order) ? parsed.order.filter((id) => typeof id === "string") : [];
|
|
678
|
+
for (const id of Object.keys(accounts)) if (!order.includes(id)) order.push(id);
|
|
679
|
+
return {
|
|
680
|
+
version: 1,
|
|
681
|
+
order,
|
|
682
|
+
accounts
|
|
683
|
+
};
|
|
684
|
+
} catch {
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
/** 多账号凭证存储:一个账号一份槽位,共用一个文档文件。 */
|
|
689
|
+
var CodeArtsAccountStore = class {
|
|
690
|
+
_doc;
|
|
691
|
+
_slots = /* @__PURE__ */ new Map();
|
|
692
|
+
_loading;
|
|
693
|
+
/** 落库串行化:多个账号的续期可能同时想写同一个文档。 */
|
|
694
|
+
_writeChain = Promise.resolve();
|
|
695
|
+
path;
|
|
696
|
+
/** 旧版单凭证文件;新文档不存在时把它收编成第一个账号。 */
|
|
697
|
+
legacyPath;
|
|
698
|
+
constructor(path, legacyPath) {
|
|
699
|
+
this.path = path;
|
|
700
|
+
this.legacyPath = legacyPath ?? join(dirname(path), ".codearts-auth.json");
|
|
701
|
+
}
|
|
702
|
+
async loaded() {
|
|
703
|
+
this._loading ??= this.load();
|
|
704
|
+
return this._loading;
|
|
705
|
+
}
|
|
706
|
+
async load() {
|
|
707
|
+
const doc = await readAccountDocument(this.path);
|
|
708
|
+
if (doc !== void 0) {
|
|
709
|
+
this.adopt(doc);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const legacy = await loadCredential(this.legacyPath);
|
|
713
|
+
const fresh = {
|
|
714
|
+
version: 1,
|
|
715
|
+
order: [],
|
|
716
|
+
accounts: {}
|
|
717
|
+
};
|
|
718
|
+
if (legacy !== void 0) {
|
|
719
|
+
const id = accountIdOf(legacy);
|
|
720
|
+
fresh.order.push(id);
|
|
721
|
+
fresh.accounts[id] = legacy;
|
|
722
|
+
}
|
|
723
|
+
this.adopt(fresh);
|
|
724
|
+
if (legacy !== void 0) await this.persistDoc();
|
|
725
|
+
}
|
|
726
|
+
adopt(doc) {
|
|
727
|
+
this._doc = doc;
|
|
728
|
+
this._slots.clear();
|
|
729
|
+
for (const [id, cred] of Object.entries(doc.accounts)) this._slots.set(id, new AccountSlot(cred, this.persisterFor(id)));
|
|
730
|
+
}
|
|
731
|
+
persisterFor(id) {
|
|
732
|
+
return async (cred) => {
|
|
733
|
+
if (this._doc === void 0) return;
|
|
734
|
+
this._doc.accounts[id] = cred;
|
|
735
|
+
await this.persistDoc();
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
persistDoc() {
|
|
739
|
+
const snapshot = this._doc;
|
|
740
|
+
const write = async () => {
|
|
741
|
+
if (snapshot !== void 0) await writeJsonAtomic(this.path, snapshot);
|
|
742
|
+
};
|
|
743
|
+
this._writeChain = this._writeChain.then(write, write);
|
|
744
|
+
return this._writeChain;
|
|
745
|
+
}
|
|
746
|
+
/** 按展示顺序返回账号摘要。 */
|
|
747
|
+
async list() {
|
|
748
|
+
await this.loaded();
|
|
749
|
+
const doc = this._doc;
|
|
750
|
+
return doc.order.filter((id) => doc.accounts[id] !== void 0).map((id) => summarizeAccount(id, doc.accounts[id]));
|
|
751
|
+
}
|
|
752
|
+
async ids() {
|
|
753
|
+
await this.loaded();
|
|
754
|
+
const doc = this._doc;
|
|
755
|
+
return doc.order.filter((id) => doc.accounts[id] !== void 0);
|
|
756
|
+
}
|
|
757
|
+
async credential(id) {
|
|
758
|
+
await this.loaded();
|
|
759
|
+
return this._doc.accounts[id];
|
|
760
|
+
}
|
|
761
|
+
/** 首个账号——卡片顶部与 CLI 的「当前」。 */
|
|
762
|
+
async current() {
|
|
763
|
+
const ids = await this.ids();
|
|
764
|
+
return ids.length === 0 ? void 0 : this._doc.accounts[ids[0]];
|
|
765
|
+
}
|
|
766
|
+
async hasCredential() {
|
|
767
|
+
return (await this.ids()).length > 0;
|
|
768
|
+
}
|
|
769
|
+
/** 新增或更新一个账号,返回它的 id。 */
|
|
770
|
+
async upsert(cred, id = accountIdOf(cred)) {
|
|
771
|
+
await this.loaded();
|
|
772
|
+
const doc = this._doc;
|
|
773
|
+
this._slots.get(id)?.invalidate();
|
|
774
|
+
doc.accounts[id] = cred;
|
|
775
|
+
if (!doc.order.includes(id)) doc.order.push(id);
|
|
776
|
+
this._slots.set(id, new AccountSlot(cred, this.persisterFor(id)));
|
|
777
|
+
await this.persistDoc();
|
|
778
|
+
await claimIfPossible(cred);
|
|
779
|
+
return id;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* 从一次 OAuth 登录结果新增/更新账号。
|
|
783
|
+
*
|
|
784
|
+
* 「再登录一次」天然就是「添加账号」:同一账号是更新,别的账号就是新增。
|
|
785
|
+
*
|
|
786
|
+
* 传了 `identity`(来自 `fetchCallerIdentity` 的稳定 user_id)就用它当账号键 ——
|
|
787
|
+
* 这正是「对同一个账号重新登录会被当成新账号」的解药;拿不到身份时退回旧行为
|
|
788
|
+
* (DPoP 公钥当键),也就是每次登录各自成一条。
|
|
789
|
+
*/
|
|
790
|
+
async upsertFromOAuth(t, label, identity) {
|
|
791
|
+
const cred = credentialFromOAuth(t, label);
|
|
792
|
+
if (identity !== void 0) {
|
|
793
|
+
cred.userId = identity.userId;
|
|
794
|
+
if (identity.userName !== "") cred.userName = identity.userName;
|
|
795
|
+
if (identity.domainId !== "") cred.domainId = identity.domainId;
|
|
796
|
+
}
|
|
797
|
+
return this.upsert(cred);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* 把一条已有账号迁移到它的稳定身份键上(同键则合并)。
|
|
801
|
+
*
|
|
802
|
+
* 用在两处:登录后回填身份(老条目已经存在时合并掉),以及 `dsh-codearts identity --fix`
|
|
803
|
+
* 清理历史遗留的重复条目。合并时保留 `storedAt` 较新的一份凭证,位置沿用目标键原有的顺序。
|
|
804
|
+
*
|
|
805
|
+
* @returns 迁移结果:`merged` 表示并入了已存在的那条,`moved` 表示只换了键,`noop` 表示键没变
|
|
806
|
+
*/
|
|
807
|
+
async adoptIdentity(id, identity) {
|
|
808
|
+
await this.loaded();
|
|
809
|
+
const doc = this._doc;
|
|
810
|
+
const existing = doc.accounts[id];
|
|
811
|
+
if (existing === void 0) return "noop";
|
|
812
|
+
const targetKey = identity.userId;
|
|
813
|
+
if (targetKey === "" || targetKey === id) {
|
|
814
|
+
doc.accounts[id] = {
|
|
815
|
+
...existing,
|
|
816
|
+
userId: identity.userId === "" ? existing.userId : identity.userId,
|
|
817
|
+
...identity.userName === "" ? {} : { userName: identity.userName },
|
|
818
|
+
...identity.domainId === "" ? {} : { domainId: identity.domainId }
|
|
819
|
+
};
|
|
820
|
+
this._slots.get(id)?.invalidate();
|
|
821
|
+
this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
|
|
822
|
+
await this.persistDoc();
|
|
823
|
+
return "noop";
|
|
824
|
+
}
|
|
825
|
+
const target = doc.accounts[targetKey];
|
|
826
|
+
const keep = target === void 0 ? existing : newerCredential(target, existing);
|
|
827
|
+
doc.accounts[targetKey] = {
|
|
828
|
+
...keep,
|
|
829
|
+
userId: identity.userId,
|
|
830
|
+
...identity.userName === "" ? {} : { userName: identity.userName },
|
|
831
|
+
...identity.domainId === "" ? {} : { domainId: identity.domainId }
|
|
832
|
+
};
|
|
833
|
+
delete doc.accounts[id];
|
|
834
|
+
doc.order = doc.order.filter((existingId) => existingId !== id);
|
|
835
|
+
if (!doc.order.includes(targetKey)) doc.order.push(targetKey);
|
|
836
|
+
this._slots.get(id)?.invalidate();
|
|
837
|
+
this._slots.delete(id);
|
|
838
|
+
this._slots.get(targetKey)?.invalidate();
|
|
839
|
+
this._slots.set(targetKey, new AccountSlot(doc.accounts[targetKey], this.persisterFor(targetKey)));
|
|
840
|
+
await this.persistDoc();
|
|
841
|
+
return target === void 0 ? "moved" : "merged";
|
|
842
|
+
}
|
|
843
|
+
/** 手工粘贴 security_token(降级态,无 AK/SK)——固定覆盖同一个「手工」账号。 */
|
|
844
|
+
async set(token, label) {
|
|
845
|
+
await this.upsert({
|
|
846
|
+
token: token.trim(),
|
|
847
|
+
label,
|
|
848
|
+
storedAt: Date.now()
|
|
849
|
+
}, MANUAL_ACCOUNT_ID);
|
|
850
|
+
}
|
|
851
|
+
async remove(id) {
|
|
852
|
+
await this.loaded();
|
|
853
|
+
const doc = this._doc;
|
|
854
|
+
this._slots.get(id)?.invalidate();
|
|
855
|
+
this._slots.delete(id);
|
|
856
|
+
delete doc.accounts[id];
|
|
857
|
+
doc.order = doc.order.filter((existing) => existing !== id);
|
|
858
|
+
await this.persistDoc();
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* 暂停 / 恢复一个账号。
|
|
862
|
+
*
|
|
863
|
+
* 只改标记,不碰凭证:恢复时不需要重新登录。重新装配槽位是因为 AccountSlot
|
|
864
|
+
* 缓存的 `_cred` 是旧对象,续期回写会把它盖回来 —— 换了对象,续期写到新文档里。
|
|
865
|
+
*/
|
|
866
|
+
async setPaused(id, paused) {
|
|
867
|
+
await this.loaded();
|
|
868
|
+
const doc = this._doc;
|
|
869
|
+
const cred = doc.accounts[id];
|
|
870
|
+
if (cred === void 0) return false;
|
|
871
|
+
doc.accounts[id] = {
|
|
872
|
+
...cred,
|
|
873
|
+
paused
|
|
874
|
+
};
|
|
875
|
+
this._slots.get(id)?.invalidate();
|
|
876
|
+
this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
|
|
877
|
+
await this.persistDoc();
|
|
878
|
+
return true;
|
|
879
|
+
}
|
|
880
|
+
/** 置顶 / 取消置顶:只改变轮转先后,不绕过冷却与并发上限。 */
|
|
881
|
+
async setPinned(id, pinned) {
|
|
882
|
+
await this.loaded();
|
|
883
|
+
const doc = this._doc;
|
|
884
|
+
const cred = doc.accounts[id];
|
|
885
|
+
if (cred === void 0) return false;
|
|
886
|
+
doc.accounts[id] = {
|
|
887
|
+
...cred,
|
|
888
|
+
pinned
|
|
889
|
+
};
|
|
890
|
+
this._slots.get(id)?.invalidate();
|
|
891
|
+
this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
|
|
892
|
+
await this.persistDoc();
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
/** shim 用:参与轮转的账号 id(排除用户暂停的)。 */
|
|
896
|
+
async dispatchIds() {
|
|
897
|
+
const paused = new Set(await this.pausedIds());
|
|
898
|
+
return (await this.ids()).filter((id) => !paused.has(id));
|
|
899
|
+
}
|
|
900
|
+
/** 被用户暂停的账号 id(账号池据此保留状态但不派活)。 */
|
|
901
|
+
async pausedIds() {
|
|
902
|
+
await this.loaded();
|
|
903
|
+
const doc = this._doc;
|
|
904
|
+
return (await this.ids()).filter((id) => doc.accounts[id]?.paused === true);
|
|
905
|
+
}
|
|
906
|
+
/** 置顶账号的 id 列表(给账号池排序用)。 */
|
|
907
|
+
async pinnedIds() {
|
|
908
|
+
await this.loaded();
|
|
909
|
+
const doc = this._doc;
|
|
910
|
+
return (await this.ids()).filter((id) => doc.accounts[id]?.pinned === true);
|
|
911
|
+
}
|
|
912
|
+
/** 清空全部账号(整体登出)。 */
|
|
913
|
+
async clear() {
|
|
914
|
+
await this.loaded();
|
|
915
|
+
for (const slot of this._slots.values()) slot.invalidate();
|
|
916
|
+
this._slots.clear();
|
|
917
|
+
this._doc = {
|
|
918
|
+
version: 1,
|
|
919
|
+
order: [],
|
|
920
|
+
accounts: {}
|
|
921
|
+
};
|
|
922
|
+
await this.persistDoc();
|
|
923
|
+
await clearCredential(this.legacyPath);
|
|
924
|
+
}
|
|
925
|
+
/** 给 shim 用:解析某账号的签名材料(内部含续期)。 */
|
|
926
|
+
async resolve(id) {
|
|
927
|
+
await this.loaded();
|
|
928
|
+
const slot = this._slots.get(id);
|
|
929
|
+
if (slot === void 0) return void 0;
|
|
930
|
+
const cred = await slot.ensureFresh();
|
|
931
|
+
return {
|
|
932
|
+
token: cred.token,
|
|
933
|
+
accessKeyId: cred.accessKeyId,
|
|
934
|
+
secretAccessKey: cred.secretAccessKey,
|
|
935
|
+
securityToken: cred.token
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* 上游报 IAM token 无效时强制续期。
|
|
940
|
+
*
|
|
941
|
+
* `seenToken` 是这次请求实际用的 token:若别的请求已经换过凭证,就别再刷一次
|
|
942
|
+
* (refresh_token 会轮换,白刷一次就多一次失败风险)。
|
|
943
|
+
*/
|
|
944
|
+
async forceRefresh(id, seenToken) {
|
|
945
|
+
await this.loaded();
|
|
946
|
+
const slot = this._slots.get(id);
|
|
947
|
+
if (slot === void 0) return void 0;
|
|
948
|
+
if (seenToken !== void 0 && slot.credential.token !== seenToken) return slot.credential;
|
|
949
|
+
return slot.forceRefresh();
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* 从磁盘重读账号文档,丢掉内存里的槽位缓存。
|
|
953
|
+
*
|
|
954
|
+
* 给「常驻守护进程」(`keeper-main.ts`)用:它在 DSH 之外续期并写回同一个文档,
|
|
955
|
+
* 所以插件这边必须定期重读,否则会一直用启动时那份快照 —— 表现为「守护进程明明
|
|
956
|
+
* 续上了,卡片还显示快过期」,更糟的是插件下一次落库会把守护进程刚写的新
|
|
957
|
+
* refresh_token 覆盖回旧的,那个号就再也续不上了。
|
|
958
|
+
*
|
|
959
|
+
* 只在**没有**在飞的续期时调用(`keepAliveLoop` 里与 `keepAlive` 互斥);
|
|
960
|
+
* 重读会把所有槽位重建,正在跑的刷新结果会被代际号拦下,不会写回。
|
|
961
|
+
*/
|
|
962
|
+
async reloadFromDisk() {
|
|
963
|
+
const doc = await readAccountDocument(this.path);
|
|
964
|
+
if (doc === void 0) return false;
|
|
965
|
+
for (const slot of this._slots.values()) slot.invalidate();
|
|
966
|
+
this.adopt(doc);
|
|
967
|
+
return true;
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* 后台保活:把所有**还能续**的账号过一遍 `ensureFresh`。
|
|
971
|
+
*
|
|
972
|
+
* 为什么需要它:`ensureFresh` 只会被「有请求进来」这条路径触发,而凭证有效期是
|
|
973
|
+
* 固定的 2 小时。用户开着 DSH 但不聊天时,没有任何请求 → 凭证裸奔到过期 → 下一次
|
|
974
|
+
* 发消息前必须先重新登录。定时调这里,只要 DSH 活着凭证就一直被续上。
|
|
975
|
+
*
|
|
976
|
+
* 只刷「距过期不足 `REFRESH_SKEW_MS`」的那些,刚从上游拿到的号不会被白刷一次:
|
|
977
|
+
* `refresh_token` 是一次性的,多余的刷新只会多一份失败风险。
|
|
978
|
+
* `stale` 的号(已确认必须重新登录)直接跳过——空转只会白烧请求。
|
|
979
|
+
*/
|
|
980
|
+
async keepAlive() {
|
|
981
|
+
await this.loaded();
|
|
982
|
+
const needsLogin = [];
|
|
983
|
+
let refreshed = 0;
|
|
984
|
+
let checked = 0;
|
|
985
|
+
for (const [id, slot] of this._slots) {
|
|
986
|
+
const before = slot.credential;
|
|
987
|
+
if (before.stale === true) {
|
|
988
|
+
needsLogin.push(id);
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
if (!before.refreshToken || !before.dpopPrivateKey || !before.clientId) continue;
|
|
992
|
+
const exp = before.expiration ? Date.parse(before.expiration) : NaN;
|
|
993
|
+
if (Number.isNaN(exp)) continue;
|
|
994
|
+
if (exp - Date.now() >= REFRESH_SKEW_MS) continue;
|
|
995
|
+
checked += 1;
|
|
996
|
+
const after = await slot.ensureFresh().catch(() => before);
|
|
997
|
+
if (after.token !== before.token) refreshed += 1;
|
|
998
|
+
if (after.stale === true) needsLogin.push(id);
|
|
999
|
+
}
|
|
1000
|
+
return {
|
|
1001
|
+
checked,
|
|
1002
|
+
refreshed,
|
|
1003
|
+
needsLogin
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
//#endregion
|
|
1008
|
+
export { codeartsAuthPath as a, writeJsonAtomic as c, startLogin as d, codeartsAccountsPath as i, defaultLoginConfig as l, CodeArtsCredentialStore as n, credentialFromOAuth as o, MANUAL_ACCOUNT_ID as r, readAccountDocument as s, CodeArtsAccountStore as t, refreshToken as u };
|