Files
deerflow-code/frontend-web/src/core/auth/sync.tsx
T

137 lines
5.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
AUTH_STATE_CHANGED_EVENT,
getAccountDisplayName,
getAccountIdentityKey,
} from "@/core/auth";
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
const AUTH_STORAGE_KEY = "deerflow.auth";
const SETTLE_DELAY_MS = 1200;
const IDENTITY_TOAST_ID = "auth-identity-changed";
function readIdentityKey(): string | null {
return getAccountIdentityKey();
}
function freshRouteForAccount(pathname: string): string {
// A thread URL belongs to the old account. Keep its workspace/agent context
// but move to a valid new conversation before the user can submit into the
// stale thread. Other pages can stay in place and are remounted below.
const chatMatch = pathname.match(/^(.*\/chats)\/[^/]+\/?$/);
return chatMatch ? `${chatMatch[1]}/new` : pathname;
}
/**
* Cross-tab auth boundary for normal pages.
*
* Same-account token re-issuance is ignored. A genuine account change clears
* account-scoped query state, remounts the page, and moves an open chat to its
* fresh-chat route without a full browser reload. Embedded/isolated tabs keep
* their sessionStorage identity and never participate in this synchronization.
*/
export function AuthSyncWatcher({
children,
disabled = false,
}: {
children?: ReactNode;
disabled?: boolean;
}) {
const lastIdentityRef = useRef<string | null>(readIdentityKey());
const [revision, setRevision] = useState(0);
const queryClient = useQueryClient();
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
if (disabled) return;
// 嵌入(iframe)态 / 独立会话态(?isolate=1):鉴权走按标签页的 sessionStorage,本就不与其它标签页
// 共享,且不应被其它标签页的 localStorage 账号变更打扰 —— 直接不挂跨标签监听。
if (isEmbedActive() || isIsolatedSession()) return;
let settleTimer: ReturnType<typeof setTimeout> | null = null;
function evaluateSettledIdentity() {
const nextIdentity = readIdentityKey();
if (nextIdentity === lastIdentityRef.current) {
return;
}
lastIdentityRef.current = nextIdentity;
void queryClient.cancelQueries();
queryClient.clear();
window.dispatchEvent(new Event(AUTH_STATE_CHANGED_EVENT));
setRevision((value) => value + 1);
if (nextIdentity === null) {
toast.info("账号已在其它页面退出", {
id: IDENTITY_TOAST_ID,
description: "当前页面已同步退出状态。",
});
// A bare legacy /login entry auto-starts the guest SSO flow. Cross-tab
// logout must stop at the explicit re-login screen instead of silently
// creating a guest session that can overwrite the account in another tab.
navigate("/login?reason=session-expired", { replace: true });
return;
}
const freshRoute = freshRouteForAccount(location.pathname);
if (freshRoute !== location.pathname) {
navigate(freshRoute, { replace: true });
}
toast.info("账号已在页面间自动同步", {
id: IDENTITY_TOAST_ID,
description: `当前账号:${getAccountDisplayName()}。无需刷新页面。`,
});
}
function handleStorage(event: StorageEvent) {
// 运行时若已切到独立会话(「外观」开关在挂载后才开启):鉴权改读本标签页 sessionStorage,
// 不应再被其它标签页的 localStorage 账号变更打扰 —— 即时忽略,无需刷新页面。
if (isEmbedActive() || isIsolatedSession()) {
return;
}
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
// handled centrally through 401 responses.
if (event.key !== AUTH_STORAGE_KEY) {
return;
}
if (settleTimer) {
clearTimeout(settleTimer);
}
settleTimer = setTimeout(evaluateSettledIdentity, SETTLE_DELAY_MS);
}
function handleSameTabAuthChange() {
// `storage` never fires in the tab that called setStoredAuth/clearStoredAuth.
// Keep the comparison baseline current so a later same-account token
// renewal from another normal page is not compared with the pre-login
// `null` identity and falsely classified as an account switch.
lastIdentityRef.current = readIdentityKey();
}
window.addEventListener("storage", handleStorage);
window.addEventListener(AUTH_STATE_CHANGED_EVENT, handleSameTabAuthChange);
return () => {
window.removeEventListener("storage", handleStorage);
window.removeEventListener(AUTH_STATE_CHANGED_EVENT, handleSameTabAuthChange);
if (settleTimer) {
clearTimeout(settleTimer);
}
};
}, [disabled, location.pathname, navigate, queryClient]);
// A keyed Fragment is transformed by the development tagger, which injects
// data-lov-id. React.Fragment only accepts key and children, so use a
// display:contents element to preserve the remount behavior without adding
// a layout box.
return children ? <div className="contents" key={revision}>{children}</div> : null;
}