flow / src /store /useAuthStore.ts
mrfakename's picture
Require sign-in, bucket-only storage, sign in via new tab when embedded
0ac416b verified
Raw History Blame Contribute Delete
6.1 kB
import { create } from "zustand";
import {
beginLogin,
CLIENT_ID,
handleRedirect,
isEmbedded,
loadSession,
refresh,
saveSession,
openAppUrl,
silentEmbeddedSession,
takeHandoff,
takeHandoffWithStorageAccess,
writeHandoff,
WRITE_SCOPES,
type HFSession,
type HFUser,
} from "../lib/hfAuth";
let pollId: ReturnType<typeof setInterval> | undefined;
const stopPoll = () => {
clearInterval(pollId);
pollId = undefined;
};
interface AuthState {
session: HFSession | null;
user: HFUser | null;
busy: boolean;
error: string | null;
configured: boolean;
/** Waiting for a sign-in window: "tab" (embedded, new tab) or "popup" (re-auth). */
pending: false | "tab" | "popup";
/** Signed in, but the token stopped working (expired / revoked / missing scope). The editor stays open; sign in again via popup. */
expired: boolean;
/** Bearer token to use for Hub and Space calls, or null when signed out. */
token: () => string | null;
/** Whether the current session was granted an OAuth scope (older sessions may lack newer ones). */
hasScope: (scope: string) => boolean;
/** Signed in with the scopes needed to write repos and the storage bucket. */
canWrite: () => boolean;
init: () => Promise<void>;
login: () => void;
/** Re-authenticate without leaving the page (popup), keeping in-memory edits. */
reauth: () => void;
/** Tries the refresh token; on failure marks the session expired. */
refreshNow: () => Promise<boolean>;
/** Embedded: pick up the popup's result, asking for storage access if cookies are partitioned. */
finishLogin: () => Promise<void>;
cancelLogin: () => void;
/** Embedded: open the full app in its own tab. */
openApp: () => void;
logout: () => void;
adopt: (s: HFSession) => void;
clearError: () => void;
reauth_: (reauth: boolean) => void;
}
export const useAuthStore = create<AuthState>((set, get) => ({
session: null,
user: null,
busy: false,
error: null,
pending: false,
expired: false,
configured: !!CLIENT_ID,
token: () => get().session?.accessToken ?? null,
hasScope: (scope) => !!get().session && get().session!.scope.split(/\s+/).includes(scope),
canWrite: () => WRITE_SCOPES.every((sc) => get().hasScope(sc)),
init: async () => {
set({ busy: true });
try {
const r = await handleRedirect();
let session = r?.session ?? null;
// New tab opened from the embed: also hand the session to the iframe when the browser allows it.
if (r?.mode === "embed") writeHandoff(r.session);
if (!session && isEmbedded) session = await silentEmbeddedSession();
if (!session) {
session = loadSession();
if (session && session.expiresAt < Date.now() + 60_000) {
try {
session = await refresh(session);
} catch {
session = null;
}
}
}
saveSession(session);
set({ session, user: session?.user ?? null, busy: false });
} catch (e) {
saveSession(null);
set({ session: null, user: null, busy: false, error: e instanceof Error ? e.message : String(e) });
}
},
login: () => get().reauth_(false),
reauth: () => get().reauth_(true),
reauth_: (reauth: boolean) => {
set({ error: null });
try {
const r = beginLogin({ reauth });
if (r === "redirect") return set({ busy: true });
if (r === "blocked") return set({ error: "The sign-in window was blocked. Allow pop-ups for this page and try again." });
// Window open: poll for its handoff cookie (only visible when third-party cookies are allowed).
set({ pending: r });
stopPoll();
const started = Date.now();
pollId = setInterval(async () => {
if (Date.now() - started > 10 * 60_000) {
stopPoll();
return set({ pending: false });
}
const s = await takeHandoff().catch(() => null);
if (s) get().adopt(s);
}, 1000);
} catch (e) {
set({ busy: false, error: e instanceof Error ? e.message : String(e) });
}
},
finishLogin: async () => {
const s = await takeHandoffWithStorageAccess().catch(() => null);
if (s) get().adopt(s);
else
set({
error:
get().pending === "popup"
? "Sign-in hasn't come through yet. Finish it in the pop-up, then try again."
: "This embedded view can't see the sign-in from the new tab (your browser keeps them apart). Keep working in the new tab, or allow storage access when asked.",
});
},
cancelLogin: () => {
stopPoll();
set({ pending: false });
},
openApp: () => {
window.open(openAppUrl(), "_blank");
},
adopt: (session) => {
stopPoll();
saveSession(session);
set({ session, user: session.user, pending: false, busy: false, error: null, expired: false });
},
refreshNow: async () => {
const s = get().session;
if (!s) return false;
try {
const next = await refresh(s);
saveSession(next);
set({ session: next, user: next.user, expired: false });
return true;
} catch {
set({ expired: true });
return false;
}
},
logout: () => {
saveSession(null);
set({ session: null, user: null, expired: false });
},
clearError: () => set({ error: null }),
}));
/** Keeps the token fresh across a long session. */
export function startTokenRefresh() {
const tick = async () => {
const st = useAuthStore.getState();
const s = st.session;
if (!s || st.expired) return;
if (s.expiresAt - Date.now() > 5 * 60_000) return;
if (!s.refreshToken) {
// No way to renew: ask for a sign-in once it has actually run out.
if (s.expiresAt < Date.now()) useAuthStore.setState({ expired: true });
return;
}
const ok = await st.refreshNow();
// A failed refresh before expiry isn't fatal yet; refreshNow marked it expired, undo until it runs out.
if (!ok && s.expiresAt > Date.now()) useAuthStore.setState({ expired: false });
};
const id = setInterval(tick, 60_000);
return () => clearInterval(id);
}