File size: 2,346 Bytes
7a35d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62fc05f
 
 
7a35d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// "Sign in with Hugging Face" for the agent's model calls. On a Space with hf_oauth enabled, the
// static host provides the OAuth client in window.huggingface.variables and the token comes back by
// redirect. Inside the Space page's iframe the sign-in runs in a new tab (HF's guidance for iframes);
// the agent then works in that tab.
import { oauthHandleRedirectIfPresent, oauthLoginUrl } from "@huggingface/hub";

const KEY = "xlerobot-sim.hf-oauth";

export function oauthAvailable() {
  return Boolean(globalThis.window?.huggingface?.variables?.OAUTH_CLIENT_ID);
}

const inIframe = () => {
  try {
    return window.self !== window.top;
  } catch {
    return true;
  }
};

/** The stored or just-returned sign-in: {accessToken, name, expires} or null. */
export async function currentLogin() {
  try {
    const result = await oauthHandleRedirectIfPresent();
    if (result) {
      const login = { accessToken: result.accessToken, name: result.userInfo?.preferred_username ?? result.userInfo?.name ?? "", expires: result.accessTokenExpiresAt?.toString?.() ?? null };
      localStorage.setItem(KEY, JSON.stringify(login));
      const url = new URL(location.href);
      for (const k of ["code", "state"]) url.searchParams.delete(k);
      history.replaceState(null, "", url);
      return login;
    }
  } catch (error) {
    console.warn("OAuth redirect:", error);
  }
  try {
    const login = JSON.parse(localStorage.getItem(KEY) ?? "null");
    if (login && (!login.expires || new Date(login.expires) > new Date())) return login;
  } catch {
    // storage may be blocked
  }
  return null;
}

export async function signIn() {
  if (inIframe()) {
    // Open the app itself in a tab; it starts the redirect there.
    const url = new URL(location.href);
    url.searchParams.set("signin", "1");
    window.open(url.toString(), "_blank", "noopener");
    return;
  }
  const scopes = window.huggingface?.variables?.OAUTH_SCOPES ?? "openid profile inference-api";
  window.location.href = (await oauthLoginUrl({ scopes })) + "&prompt=consent";
}

export function signOut() {
  try {
    localStorage.removeItem(KEY);
  } catch {
    // ignore
  }
}

/** True when the page was opened to sign in (from the iframe's button). */
export function signInRequested() {
  return new URL(location.href).searchParams.get("signin") === "1";
}