Spaces:
Running
Running
File size: 9,696 Bytes
46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 5d3283b 46d9e41 | 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | // "Sign in with Hugging Face": OAuth 2.0 authorization code flow with PKCE, entirely in the
// browser (no backend, no client secret). The token it returns calls Hugging Face Inference
// Providers on the user's own account (scope "inference-api").
//
// The sign-in runs in a popup so the app (and its running Linux VM) never reloads. The popup
// lands on oauth.html, which exchanges the code for a token and hands the session back over
// a BroadcastChannel: the app is cross-origin isolated (COOP), so the popup has no opener.
import { HF_OAUTH_CLIENT_ID } from "./config.js";
const HF = "https://huggingface.co";
export const HF_SCOPES = "openid profile inference-api";
const PENDING = "lwa-hf-oauth-pending"; // localStorage: what the callback needs to finish
const CHANNEL = "lwa-hf-oauth";
const SESSION = (id) => `lwa-hf-session:${id}`;
/** The OAuth app's client ID: from config.js, or the one Hugging Face injects into Spaces with hf_oauth. */
export function hfClientId() {
return HF_OAUTH_CLIENT_ID || globalThis.huggingface?.variables?.OAUTH_CLIENT_ID || "";
}
export const hfSignInAvailable = () => !!hfClientId();
/**
* True inside an iframe, e.g. the Space page on huggingface.co. There the browser keeps
* this app's storage separate from the same app in its own tab (storage partitioning),
* and isolation cuts the popup's link back, so the sign-in popup can't hand its result to
* the embedded app. Sign-in is then offered in the app's own tab instead.
*/
export function embedded() {
try { return window.top !== window.self; } catch { return true; }
}
export const standaloneUrl = () => new URL("./", document.baseURI).href;
export const hfRedirectUri = () => new URL("oauth.html", document.baseURI).href;
const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const random = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
async function tokenRequest(params) {
let res;
try {
res = await fetch(`${HF}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(params),
});
} catch (err) { throw new Error(`Couldn't reach Hugging Face (${err.message})`); }
const j = await res.json().catch(() => ({}));
if (!res.ok || !j.access_token) throw new Error(j.error_description || j.error || `Sign-in failed (HTTP ${res.status})`);
return j;
}
async function userInfo(accessToken) {
try {
const res = await fetch(`${HF}/oauth/userinfo`, { headers: { Authorization: `Bearer ${accessToken}` } });
const u = await res.json();
return { name: u.name || u.preferred_username || "", username: u.preferred_username || "", avatarUrl: u.picture || "" };
} catch { return { name: "", username: "", avatarUrl: "" }; }
}
const toSession = (t, user, prev = {}) => ({
accessToken: t.access_token,
refreshToken: t.refresh_token ?? prev.refreshToken ?? null,
expiresAt: t.expires_in ? Date.now() + t.expires_in * 1000 : null,
user: user ?? prev.user ?? null,
clientId: prev.clientId ?? hfClientId(),
});
let cancelPending = null;
// Messages between the app and the oauth.html popup go over a BroadcastChannel, with
// localStorage "storage" events as a backup (both same-origin only). The popup only
// forwards the code; the app, which holds the PKCE verifier in memory, does the token
// exchange. So a callback page that loads twice, or late, can't break the sign-in.
const MSG_KEY = "lwa-hf-oauth-msg";
function postMsg(msg) {
try { const ch = new BroadcastChannel(CHANNEL); ch.postMessage(msg); ch.close(); } catch {}
try { localStorage.setItem(MSG_KEY, JSON.stringify({ ...msg, nonce: Math.random() })); } catch {}
}
function onMsg(handler) {
let ch = null;
try { ch = new BroadcastChannel(CHANNEL); ch.onmessage = ({ data }) => handler(data); } catch {}
const onStorage = (e) => { if (e.key === MSG_KEY && e.newValue) { try { handler(JSON.parse(e.newValue)); } catch {} } };
addEventListener("storage", onStorage);
return () => { ch?.close(); removeEventListener("storage", onStorage); };
}
/**
* Opens the Hugging Face sign-in popup. Resolves with a session
* { accessToken, refreshToken, expiresAt, user: { name, username, avatarUrl } }.
* Must be called from a click (popups are otherwise blocked).
*/
export async function signInWithHuggingFace() {
const clientId = hfClientId();
if (!clientId) throw new Error("Sign in with Hugging Face isn't set up for this app yet. Use an access token instead.");
cancelPending?.();
try { localStorage.removeItem(PENDING); } catch {} // from older versions
const verifier = random(48);
const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
const state = random(16);
const redirectUri = hfRedirectUri();
const url = new URL(`${HF}/oauth/authorize`);
for (const [k, v] of Object.entries({
client_id: clientId, redirect_uri: redirectUri, response_type: "code", scope: HF_SCOPES,
state, code_challenge: challenge, code_challenge_method: "S256",
})) url.searchParams.set(k, v);
const w = 520, hgt = 720;
const popup = window.open(url.href, "lwa-hf-signin",
`popup,width=${w},height=${hgt},left=${Math.round(screenX + (outerWidth - w) / 2)},top=${Math.round(screenY + (outerHeight - hgt) / 2)}`);
if (!popup) throw new Error("Your browser blocked the sign-in window. Allow pop-ups for this site and try again.");
return new Promise((resolve, reject) => {
let result = null; // the finished session, kept to answer repeated callbacks
let exchanging = false;
const stop = onMsg(async (m) => {
if (m?.type !== "code" || m.state !== state) return;
if (result) return postMsg({ type: "ack", state, ok: true, name: result.user?.name ?? "" });
if (exchanging) return; // the same code again while we're already using it
if (m.error) {
postMsg({ type: "ack", state, ok: false, error: m.error });
return finish(reject, new Error(m.error));
}
exchanging = true;
try {
const t = await tokenRequest({ grant_type: "authorization_code", code: m.code, redirect_uri: redirectUri, client_id: clientId, code_verifier: verifier });
result = toSession(t, await userInfo(t.access_token), { clientId });
postMsg({ type: "ack", state, ok: true, name: result.user?.name ?? "" });
finish(resolve, result, 15_000); // keep answering a reloaded callback for a while
} catch (err) {
postMsg({ type: "ack", state, ok: false, error: err.message });
finish(reject, err);
}
});
const timer = setTimeout(() => finish(reject, new Error("Sign-in timed out.")), 10 * 60 * 1000);
let settled = false;
function finish(fn, value, linger = 0) {
if (settled) return;
settled = true;
clearTimeout(timer);
cancelPending = null;
setTimeout(stop, linger);
fn(value);
}
cancelPending = () => finish(reject, Object.assign(new Error("Sign-in cancelled."), { cancelled: true }));
});
}
/** Stops waiting for a sign-in started with signInWithHuggingFace. */
export const cancelSignIn = () => cancelPending?.();
/**
* Runs in oauth.html: forwards the code (or error) from the redirect to the app and waits
* for its answer. Resolves with { ok, name } or rejects with the reason.
*/
export function completeSignIn() {
const q = new URLSearchParams(location.search);
const state = q.get("state");
const msg = { type: "code", state, code: q.get("code"), error: q.get("error") ? (q.get("error_description") || q.get("error")) : null };
if (!state || (!msg.code && !msg.error)) return Promise.reject(new Error("This page should be opened by Hugging Face after signing in. Start again from LocalWebAgent."));
return new Promise((resolve, reject) => {
const stop = onMsg((m) => {
if (m?.type !== "ack" || m.state !== state) return;
clearInterval(resend); clearTimeout(giveUp); stop();
m.ok ? resolve(m) : reject(new Error(m.error || "Sign-in failed."));
});
postMsg(msg);
const resend = setInterval(() => postMsg(msg), 1000);
const giveUp = setTimeout(() => {
clearInterval(resend); stop();
reject(new Error("LocalWebAgent didn't answer. Keep its tab open, then press Sign in with Hugging Face again."));
}, 20_000);
});
}
// ---------- stored sessions (one per saved API model that uses sign-in) ----------
export function loadSession(id) {
try { return JSON.parse(localStorage.getItem(SESSION(id)) || "null"); } catch { return null; }
}
export function saveSession(id, session) {
try { localStorage.setItem(SESSION(id), JSON.stringify(session)); } catch {}
}
export function deleteSession(id) {
try { localStorage.removeItem(SESSION(id)); } catch {}
}
export const sessionExpired = (s) => !!s?.expiresAt && s.expiresAt < Date.now() + 30_000;
/**
* The session's access token, refreshed first if it is about to expire and Hugging Face
* gave a refresh token. Throws when the user has to sign in again.
*/
export async function freshAccessToken(id) {
const s = loadSession(id);
if (!s?.accessToken) throw new Error("Not signed in to Hugging Face. Open the Model Manager and sign in.");
if (!sessionExpired(s)) return s.accessToken;
if (!s.refreshToken) throw new Error("Your Hugging Face sign-in has expired. Open the Model Manager and sign in again.");
const t = await tokenRequest({ grant_type: "refresh_token", refresh_token: s.refreshToken, client_id: s.clientId || hfClientId() });
const next = toSession(t, null, s);
saveSession(id, next);
return next.accessToken;
}
|