Files
deerflow-code/frontend-web/src/core/auth/session-validation.ts
T

93 lines
3.7 KiB
TypeScript

import { getAccountIdentityKey, type LoginByUsernameResponse } from "./index";
type StoredAccount = LoginByUsernameResponse | null;
const RECENT_LOGIN_TTL_MS = 15_000;
const recentSuccessfulLogins = new Map<string, { userId: string; expiresAt: number }>();
/** A fresh login response is already server-validated; avoid an immediate duplicate `/me`. */
export function rememberSuccessfulLogin(auth: LoginByUsernameResponse, now = Date.now()): void {
if (!hasAccountSession(auth)) return;
recentSuccessfulLogins.set(auth.access_token, {
userId: auth.user_id,
expiresAt: now + RECENT_LOGIN_TTL_MS,
});
}
export function isRecentlyAuthenticatedLogin(auth: StoredAccount, now = Date.now()): boolean {
if (!hasAccountSession(auth)) return false;
for (const [token, record] of recentSuccessfulLogins) {
if (record.expiresAt <= now) recentSuccessfulLogins.delete(token);
}
const record = recentSuccessfulLogins.get(auth.access_token);
return Boolean(record && record.expiresAt > now && record.userId === auth.user_id);
}
export type AccountAccess =
| { status: "allowed"; auth: StoredAccount }
| { status: "unauthorized"; reason?: "session-expired" };
/** Compare credentials before applying a response from an earlier request. */
export function isSameAccountSession(current: StoredAccount, requested: StoredAccount): boolean {
return current?.access_token === requested?.access_token && current?.user_id === requested?.user_id;
}
/**
* Compare the stable account principal while deliberately ignoring a renewed
* access token. A same-account login in another tab must be revalidated, but
* it must not tear down the already mounted workspace (and its iframe tree)
* while that validation is in flight.
*/
export function isSameAccountIdentity(current: StoredAccount, requested: StoredAccount): boolean {
if (current === requested) return true;
if (!current || !requested) return false;
const currentIdentity = getAccountIdentityKey(current);
const requestedIdentity = getAccountIdentityKey(requested);
return currentIdentity !== null && currentIdentity === requestedIdentity;
}
export function hasAccountSession(auth: StoredAccount): auth is LoginByUsernameResponse {
return Boolean(typeof auth?.user_id === "string" && auth.user_id.trim()
&& typeof auth.access_token === "string" && auth.access_token.trim());
}
/** Validate an existing session without fetching login options on page entry. */
export async function checkAccountAccess({
auth,
baseURL,
signal,
allowLegacyAnonymous = false,
fetcher = fetch,
}: {
auth: StoredAccount;
baseURL: string;
signal?: AbortSignal;
allowLegacyAnonymous?: boolean;
fetcher?: typeof fetch;
}): Promise<AccountAccess> {
if (!hasAccountSession(auth)) {
return allowLegacyAnonymous ? { status: "allowed", auth: null } : { status: "unauthorized" };
}
const response = await fetcher(`${baseURL}/api/v1/auth/me`, {
credentials: "include",
cache: "no-store",
headers: { Authorization: `Bearer ${auth.access_token}` },
signal,
});
if (response.status === 401) return { status: "unauthorized", reason: "session-expired" };
if (!response.ok) throw new Error("暂时无法验证登录状态,请稍后重试");
const user = await response.json() as Record<string, unknown> | null;
if (!user || typeof user.id !== "string" || typeof user.email !== "string"
|| typeof user.system_role !== "string" || typeof user.needs_setup !== "boolean") {
throw new Error("服务器返回的登录信息不完整,请稍后重试");
}
if (user.id !== auth.user_id) return { status: "unauthorized", reason: "session-expired" };
return {
status: "allowed",
auth: { ...auth, email: user.email, system_role: user.system_role, needs_setup: user.needs_setup },
};
}