41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import { CorpConfig } from "../config/types.js";
|
|
import { AuthenticationError } from "../errors.js";
|
|
import { createAuthClient } from "../http/factory.js";
|
|
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
|
|
|
|
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
|
return {
|
|
accesstoken: corp.credentials.accessToken,
|
|
corpid: corp.corpId || corp.credentials.corpId,
|
|
staffid: corp.staffId || corp.credentials.staffId,
|
|
};
|
|
}
|
|
|
|
export async function createEkbClient(corp: CorpConfig) {
|
|
const canRefresh = canRefreshCorpAccessToken(corp);
|
|
|
|
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
|
if (canRefresh && corp.auth?.expiresAt) {
|
|
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
|
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
|
await refreshSingleCorpAccessToken(corp);
|
|
}
|
|
}
|
|
|
|
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
|
return createAuthClient({
|
|
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
|
getHeaders: () => getEkbHeaders(corp),
|
|
retryUnauthorized: canRefresh,
|
|
...(canRefresh
|
|
? {
|
|
onUnauthorized: async () => {
|
|
await refreshSingleCorpAccessToken(corp);
|
|
},
|
|
}
|
|
: {
|
|
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
|
|
}),
|
|
});
|
|
}
|