fix: recover expired Basic Auth sessions in the current tab

This commit is contained in:
ji ruo committed 2026-11-10 16:28:23 +08:00
1 parent a05a886d3d
commit 0ff2130f46
7 files changed
+275 -20

No files matched your search

+41 -11
View File
@@ -144,10 +144,28 @@ function getToken(): string | null {
return localStorage.getItem("artex_token");
}
let basicAuthReloading = false;
let basicAuthProbe: Promise<void> | null = null;
// Renew the outer gate through a page navigation, where the browser can send
// Basic credentials without replacing an API request's Bearer authorization.
// Keep the admin token and collapse concurrent failures into one reload.
export async function apiFetch(input: string, init?: RequestInit): Promise<Response> {
if (basicAuthReloading) throw new Error("访问验证已过期,正在重新验证");
const response = await fetch(input, init);
if (basicAuthReloading) throw new Error("访问验证已过期,正在重新验证");
if (response.status === 401 && response.headers.get("X-Artex-Auth") === "basic") {
basicAuthReloading = true;
window.location.reload();
throw new Error("访问验证已过期,正在重新验证");
}
return response;
}
export async function http<T>(path: string, init?: RequestInit): Promise<T> {
if (MOCK) return mockHandle<T>(init?.method ?? "GET", path, init?.body ?? null);
const token = getToken();
const r = await fetch(`/api${path}`, {
const r = await apiFetch(`/api${path}`, {
...init,
headers: {
...(init?.body ? { "Content-Type": "application/json" } : {}),
@@ -236,7 +254,19 @@ export function openSSE(path: string): EventSource {
// Same-origin streams already send cookies. Only opt into cross-port cookies
// for the local Next/Go dev pair; keep custom remote SSE endpoints unchanged.
const local = ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname);
return new EventSource(url, { withCredentials: local && target.hostname === window.location.hostname });
const source = new EventSource(url, { withCredentials: local && target.hostname === window.location.hostname });
source.addEventListener("error", () => {
// EventSource hides the response status. Probe a same-origin auth endpoint
// to distinguish an expired gate from an ordinary stream/network failure.
if (basicAuthProbe !== null || basicAuthReloading) return;
basicAuthProbe = apiFetch("/api/auth/status", { cache: "no-store" })
.then(() => undefined)
.catch(() => undefined)
.finally(() => {
basicAuthProbe = null;
});
});
return source;
}
const get = <T>(p: string) => http<T>(p);
@@ -554,7 +584,7 @@ export const api = {
const fd = new FormData();
for (const f of files) fd.append("file", f);
const token = getToken();
const r = await fetch(`/api/workspace/upload?path=${encodeURIComponent(dir)}`, {
const r = await apiFetch(`/api/workspace/upload?path=${encodeURIComponent(dir)}`, {
method: "POST",
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
body: fd,
@@ -569,7 +599,7 @@ export const api = {
blob = new Blob([`(demo)${path} 的下载内容示例。`], { type: "text/plain" });
} else {
const token = getToken();
const r = await fetch(`/api/workspace/download?path=${encodeURIComponent(path)}`, {
const r = await apiFetch(`/api/workspace/download?path=${encodeURIComponent(path)}`, {
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
});
if (!r.ok) throw new Error(`下载失败: ${r.status}`);
@@ -729,7 +759,7 @@ export const api = {
for (const [k, v] of findingFilterParams(opts.filters)) p.set(k, v);
}
const token = getToken();
const r = await fetch(`/api/exploration/findings/export?${p.toString()}`, {
const r = await apiFetch(`/api/exploration/findings/export?${p.toString()}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!r.ok) throw new Error(`export: ${r.status}`);
@@ -807,7 +837,7 @@ export const api = {
contextTask?: string,
) => {
const token = getToken();
const response = await fetch(
const response = await apiFetch(
`/api/exploration/findings/${id}/traffic/${bindingId}/body?side=${side}&download=1${contextTask ? `&context_task=${encodeURIComponent(contextTask)}` : ""}`,
{ headers: token ? { Authorization: `Bearer ${token}` } : {} },
);
@@ -1081,7 +1111,7 @@ export const api = {
report: async (task?: string) => {
if (MOCK) return mockReport(task);
const token = getToken();
const r = await fetch(`/api/report${tq(task)}`, {
const r = await apiFetch(`/api/report${tq(task)}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!r.ok) throw new Error(`report: ${r.status}`);
@@ -1109,7 +1139,7 @@ export const api = {
const fd = new FormData();
for (const f of files) fd.append("file", f);
const token = getToken();
const r = await fetch(`/api/chat/upload?scope=${scope}&id=${encodeURIComponent(id)}`, {
const r = await apiFetch(`/api/chat/upload?scope=${scope}&id=${encodeURIComponent(id)}`, {
method: "POST",
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
body: fd,
@@ -1369,7 +1399,7 @@ export const api = {
const fd = new FormData();
fd.append("file", file);
const token = getToken();
const r = await fetch(`/api/skills/upload${overwrite ? "?overwrite=true" : ""}`, {
const r = await apiFetch(`/api/skills/upload${overwrite ? "?overwrite=true" : ""}`, {
method: "POST",
body: fd,
headers: token ? { Authorization: `Bearer ${token}` } : {},
@@ -1458,7 +1488,7 @@ export const api = {
interceptGetToolConfig: async (): Promise<{ enabled_tools: string[] }> => {
if (MOCK) return { enabled_tools: ["bash"] };
const token = getToken();
const r = await fetch("/api/intercept/tool-config", {
const r = await apiFetch("/api/intercept/tool-config", {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!r.ok) throw new Error(await r.text());
@@ -1467,7 +1497,7 @@ export const api = {
interceptSetToolConfig: async (enabledTools: string[]): Promise<void> => {
if (MOCK) return;
const token = getToken();
const r = await fetch("/api/intercept/tool-config", {
const r = await apiFetch("/api/intercept/tool-config", {
method: "PUT",
headers: {
"Content-Type": "application/json",