fix(auth): renew cached subdomain tokens before bounded request replay

This commit is contained in:
gitea committed 2026-10-20 17:57:41 +08:00
1 parent fac81b08e8
commit 53689e89d0
6 files changed
+365 -326

No files matched your search

+13 -22
View File
@@ -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);
}
}
},
],
},
});
}