merge: integrate review-10-client-auth-refresh
This commit is contained in:
commit
2be973ddf4
6 files changed
+411
-372
No files matched your search
Vendored
+333
-333
File diff suppressed because it is too large.
Load diff
@@ -58,3 +58,5 @@ src/core/
|
||||
- `getCorpProvisionalAuthLink` 显式指定 `staffId` 时需要已配置的 OpenAPI 密钥;旧员工的 Session Token 不会伪装成目标员工。
|
||||
- 临时换签只返回独立链接,不修改默认身份、Token 或缓存。只有 `persistStaff=true` 才把目标身份、Token、有效期和员工名称一起持久化;同一身份的普通续期保持原行为。
|
||||
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
|
||||
|
||||
子域客户端在 401 后使缓存失效、重新换票,并从新缓存读取请求头重放原请求一次;同一客户端无需重建。持续鉴权失败停止重试,POST 请求体在重放时保持一致。
|
||||
+13
-22
@@ -1,4 +1,4 @@
|
||||
import ky, { KyInstance } from "ky";
|
||||
import ky, { KyInstance, type BeforeRequestState } from "ky";
|
||||
|
||||
export interface CreateClientOptions {
|
||||
prefixUrl: string;
|
||||
@@ -24,14 +24,12 @@ export function createClient(options: CreateClientOptions): KyInstance {
|
||||
}
|
||||
|
||||
export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
const replays = new WeakMap<object, ReturnType<BeforeRequestState["request"]["clone"]>>();
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
timeout: options.timeout ?? 30000,
|
||||
retry: {
|
||||
limit: options.retryUnauthorized === false ? 0 : 1,
|
||||
methods: ["get", "post", "put", "delete", "patch"],
|
||||
statusCodes: [401],
|
||||
},
|
||||
// Authentication replay is handled once below; nested retries must not renew repeatedly.
|
||||
retry: 0,
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
async ({ request }) => {
|
||||
@@ -41,6 +39,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
if (options.onUnauthorized && options.retryUnauthorized !== false) replays.set(request, request.clone());
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
@@ -52,7 +51,10 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
errorType === "UnauthenticatedException" ||
|
||||
errorType === "UnauthorizedException";
|
||||
|
||||
if (isAuthError && options.onUnauthorized) {
|
||||
if (isAuthError && options.onUnauthorized && options.retryUnauthorized !== false) {
|
||||
const replay = replays.get(request);
|
||||
replays.delete(request);
|
||||
if (!replay) throw new Error("Authentication replay request is unavailable");
|
||||
// 触发自动续杯刷新 Token
|
||||
await options.onUnauthorized();
|
||||
|
||||
@@ -60,30 +62,19 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
const freshHeaders = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(freshHeaders)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
replay.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
return ky(request);
|
||||
// Ky's Request.clone type omits Bun's extra Headers methods; the runtime object is unchanged.
|
||||
return ky(replay as unknown as Request, { retry: 0, timeout: options.timeout ?? 30000 });
|
||||
}
|
||||
if (isAuthError && options.onAuthFailure) {
|
||||
throw options.onAuthFailure(response);
|
||||
}
|
||||
replays.delete(request);
|
||||
return response;
|
||||
},
|
||||
],
|
||||
beforeRetry: [
|
||||
async ({ request }) => {
|
||||
if (options.onUnauthorized) {
|
||||
await options.onUnauthorized();
|
||||
}
|
||||
const headers = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -119,12 +119,14 @@ export async function getScriptEngineClient(
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getScriptEngineClient(corp, platformId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -178,12 +180,14 @@ export async function getScriptEngineClient(
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoJwt}`,
|
||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getScriptEngineClient(corp, platformId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { getScriptEngineClient, clearScriptEngineClientCache } from "./script-engine-client.js";
|
||||
import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js";
|
||||
const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE;
|
||||
afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; });
|
||||
for (const kind of ["piper", "easo", "unity"] as const) {
|
||||
for (const denied of [false, true]) {
|
||||
test(`${kind} replaces cached credentials and replays a POST at most once (denied=${denied})`, async () => {
|
||||
process.env.HOSE_TOKENS_FILE = join(mkdtempSync(join(tmpdir(), "hose-renew-")), "tokens.json"); resetTokenStoreMemory();
|
||||
const corp = { id: `renew-${kind}-${denied}`, source: "manual", credentials: { accessToken: "source", corpId: "corp", staffId: "staff" } } as any;
|
||||
const shared = { sourceAccessToken: "source", expiresAt: Date.now() + 3600000 };
|
||||
setCorpTokens(corp.id, { piper: { ...shared, easJwt: "stale", hoseToken: "old-hose" }, unity: { ...shared, unityJwt: "stale" }, eas: { ...shared, easToken: "stale", unityJwt: "stale", hoseToken: "old-hose" } });
|
||||
const sent: Array<{ auth: string | null; body: string }> = [];
|
||||
globalThis.fetch = (async (input: any, init: any) => {
|
||||
const req = input instanceof Request ? input : new Request(input, init);
|
||||
if (req.url.includes("/grant/")) return Response.json({ data: "new-hose" });
|
||||
if (req.url.includes("/actions/jwt")) return Response.json({ id: "fresh" });
|
||||
if (req.url.includes("/realms/")) return Response.json({ value: { accessToken: "fresh" } });
|
||||
sent.push({ auth: req.headers.get("authorization"), body: await req.text() });
|
||||
return denied || req.headers.get("authorization") === "Bearer stale" ? new Response("expired", { status: 401 }) : Response.json({ ok: true });
|
||||
}) as any;
|
||||
const client = kind === "piper" ? await getScriptEngineClient(corp, "app") : kind === "easo" ? (await getEasoClient(corp)).client : (await getUnityClient(corp)).client;
|
||||
const request = client.post("api/review", { json: { amount: 42 } }).json();
|
||||
if (denied) await expect(request).rejects.toThrow(); else expect(await request).toEqual({ ok: true });
|
||||
expect(sent).toEqual([{ auth: "Bearer stale", body: '{"amount":42}' }, { auth: "Bearer fresh", body: '{"amount":42}' }]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -138,9 +138,11 @@ function invalidateEasoCache(corpId: string): void {
|
||||
function invalidateUnityCache(corpId: string): void {
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.unity) {
|
||||
if (persisted?.unity || persisted?.eas) {
|
||||
const next = { ...persisted };
|
||||
delete next.unity;
|
||||
// EASO also persists the Unity JWT; do not resurrect the rejected token through that fallback.
|
||||
delete next.eas;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
@@ -184,13 +186,15 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedToken}`,
|
||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateEasoCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getEasoClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -262,13 +266,15 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoToken}`,
|
||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateEasoCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getEasoClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -314,10 +320,12 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
Authorization: `Bearer ${unityMemoryCache.get(cacheKey)?.token ?? cachedJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateUnityCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getUnityClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -364,10 +372,12 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
Authorization: `Bearer ${unityMemoryCache.get(cacheKey)?.token ?? unityJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateUnityCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getUnityClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user