const TOKEN_KEY = "gsfdc_agent_token" let sessionWatch: number | null = null type AgentProfile = { username: string displayName: string canManage?: boolean } export function useAgentAuth() { const token = useState("agent-token", () => null) const username = useState("agent-username", () => null) const displayName = useState("agent-display-name", () => null) const ready = useState("agent-auth-ready", () => false) const { get } = useSiteApi() function readStored() { if (!import.meta.client) return null return window.localStorage.getItem(TOKEN_KEY) } function persist(next: string | null) { if (!import.meta.client) return if (next) window.localStorage.setItem(TOKEN_KEY, next) else window.localStorage.removeItem(TOKEN_KEY) } async function refreshProfile() { if (!token.value) { username.value = null displayName.value = null return null } try { const me = await get("/auth/agent/me", token.value) username.value = me.username displayName.value = me.displayName || me.username return me } catch (exc: any) { const status = Number(exc?.statusCode || exc?.response?.status || 0) if (status === 401 || status === 403) { token.value = null username.value = null displayName.value = null persist(null) } return null } } function takeHashToken() { if (!import.meta.client) return "" const hash = new URLSearchParams(window.location.hash.replace(/^#/, "")) const handed = hash.get("agentToken") || "" if (!handed) return "" hash.delete("agentToken") const next = hash.toString() const url = `${window.location.pathname}${window.location.search}${next ? `#${next}` : ""}` window.history.replaceState(null, "", url) return handed } async function ensure() { if (!import.meta.client) return const handed = takeHashToken() if (handed) { await setSession(handed) return } if (ready.value) return const stored = readStored() token.value = stored if (stored) await refreshProfile() ready.value = true if (token.value) watchSession() } async function setSession(accessToken: string) { token.value = accessToken persist(accessToken) ready.value = true watchSession() await refreshProfile() } function clearSession() { token.value = null username.value = null displayName.value = null persist(null) } function dropAgentSession(accessToken: string) { const stored = readStored() if (accessToken !== token.value && accessToken !== stored) return clearSession() } function watchSession() { if (!import.meta.client || sessionWatch !== null) return const tick = () => { if (token.value) void refreshProfile() } sessionWatch = window.setInterval(tick, 4000) window.addEventListener("focus", tick) } const isAuthed = computed(() => Boolean(token.value)) return { token, username, displayName, ready, isAuthed, ensure, setSession, clearSession, dropAgentSession, refreshProfile, } }