File size: 21,266 Bytes
e46c62c
6a0e679
7c19c2c
e46c62c
7c19c2c
 
6a0e679
6c53080
d3a0bca
 
 
 
 
7f00c04
713fd2f
7f00c04
 
 
7c19c2c
6a0e679
 
e46c62c
6c53080
0ae3824
7f00c04
 
 
 
e46c62c
 
 
 
 
 
 
7f00c04
 
 
 
 
 
 
 
 
 
7c19c2c
7f00c04
 
 
7c19c2c
 
 
 
 
 
7f00c04
 
 
 
 
 
 
 
 
 
 
b35e2da
 
7f00c04
 
 
b35e2da
 
6f20c5e
 
 
 
b35e2da
 
6f20c5e
 
b35e2da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f00c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b72dab
 
 
d3a0bca
4b72dab
 
 
 
e46c62c
 
 
4b72dab
 
e46c62c
 
 
 
4b72dab
 
 
 
e46c62c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f00c04
 
 
 
6f20c5e
f7bd4a3
 
 
6a0e679
4653b37
 
f7bd4a3
7f00c04
6a0e679
4653b37
6a0e679
4653b37
 
6a0e679
4653b37
6a0e679
4653b37
 
6a0e679
7f00c04
 
 
 
0ae3824
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713fd2f
7f00c04
 
 
713fd2f
7f00c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b72dab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f00c04
 
 
 
 
 
7c19c2c
7f00c04
 
 
a88eaab
 
 
 
 
7f00c04
 
 
 
 
 
 
 
 
 
 
 
7aed87d
7f00c04
 
 
 
 
713fd2f
7f00c04
e46c62c
7f00c04
 
713fd2f
 
 
 
 
 
 
 
e46c62c
 
 
6c53080
e46c62c
7f00c04
 
7c19c2c
 
 
 
 
0ae3824
7c19c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a0e679
7c19c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c53080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ae3824
6c53080
 
7c19c2c
 
 
 
 
 
 
 
e46c62c
 
 
 
7c19c2c
7f00c04
7c19c2c
 
 
7f00c04
7c19c2c
7f00c04
7c19c2c
7f00c04
 
6a0e679
 
7c19c2c
6a0e679
 
 
6f20c5e
f7bd4a3
 
7c19c2c
 
 
 
6a0e679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ae3824
6a0e679
 
 
 
 
 
b35e2da
6a0e679
 
 
 
7c19c2c
7f00c04
7c19c2c
 
 
6a0e679
7f00c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46c62c
 
 
 
6a0e679
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
const STORAGE_KEY = "hfviewer:space-native-oauth:v2";
const START_URL = "https://hfviewer.com/api/hf_space_oauth/start";
const CONSUME_URL = "https://hfviewer.com/api/hf_space_oauth/consume";
const DESTINATION_URL = "https://hfviewer.com/api/hf_space_oauth/destination";
const POLL_INTERVAL_MS = 800;
const FLOW_TIMEOUT_MS = 5 * 60 * 1000;
const PREPARE_REFRESH_MS = 4 * 60 * 1000;
const AUTH_CHANGED_EVENT = "hfviewer-space-auth-changed";
// The Space shell intercepts canonical hfviewer.com links during capture and
// treats every root-path URL as "return to the Space landing page", even when
// its query opens an account view. Use the canonicalizing www host so these
// remain ordinary external links; its 301 preserves the full query string.
const ACCOUNT_DESTINATION_ORIGIN = "https://www.hfviewer.com";
const authHost = document.getElementById("hfnx-auth");
const compactAuthHost = document.getElementById("sx-auth");

let oauthResult = readStoredResult();
let rendering = false;
let activeFlow = null;
let preparedFlow = null;
let preparePromise = null;
let accountDestinationLinks = [];
let lastAnnouncedAuthIdentity = null;
let nativeLoginPopover = null;

function readStoredResult() {
  try {
    const value = localStorage.getItem(STORAGE_KEY);
    const result = value ? JSON.parse(value) : null;
    const expiresAt = Number(result?.spaceSession?.expiresAt || 0) * 1000;
    if (!result || !expiresAt || expiresAt <= Date.now()) {
      localStorage.removeItem(STORAGE_KEY);
      return null;
    }
    return result;
  } catch {
    return null;
  }
}

function writeStoredResult(value) {
  try {
    if (value) localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
    else localStorage.removeItem(STORAGE_KEY);
  } catch {
    // Keep the current-tab session even when durable storage is unavailable.
  }
}

function randomFlowValue() {
  const bytes = new Uint8Array(32);
  crypto.getRandomValues(bytes);
  return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
}

function userFromResult(result) {
  const raw = result?.userInfo || result?.userinfo || result?.user_info || result?.user || {};
  const username = String(
    raw.preferred_username || raw.preferredUsername || raw.username || raw.name || ""
  ).trim();
  if (!username) return null;
  return {
    username,
    name: String(raw.name || username).trim(),
    picture: String(raw.picture || raw.avatar_url || raw.avatarUrl || "").trim(),
    profile: String(raw.profile || `https://huggingface.co/${encodeURIComponent(username)}`).trim(),
    subject: String(raw.sub || raw.id || "").trim(),
    email: String(raw.email || "").trim().toLowerCase(),
  };
}

function trackAuthEvent(eventName, properties = {}) {
  try {
    const productContext =
      window.HFVIEWER_PRODUCT_CONTEXT && typeof window.HFVIEWER_PRODUCT_CONTEXT === "object"
        ? window.HFVIEWER_PRODUCT_CONTEXT
        : {};
    window.hfviewerAnalyticsBridge?.capture?.(eventName, {
      product_surface: "hf_space",
      space_repo: String(productContext.space_repo || "unknown"),
      space_revision: String(productContext.space_revision || "unknown"),
      auth_provider: "hugging_face",
      ...properties,
    });
  } catch {
    // Authentication must remain independent of analytics availability.
  }
}

function identifyAuthenticatedUser(user, source) {
  if (!user?.username) return;
  try {
    window.hfviewerAnalyticsBridge?.identifyHfSession?.(
      {
        authenticated: true,
        email: user.email || "",
        user: {
          id: user.subject || "",
          username: user.username,
          name: user.name || user.username,
          email: user.email || "",
        },
      },
      source || "hf_space_native_oauth"
    );
  } catch {
    // Consent-gated identity is best effort only.
  }
}

function keepReleasePills() {
  if (!authHost) return [];
  return Array.from(authHost.children).filter((element) =>
    element.classList.contains("hfnx-auth__pill")
  );
}

function makeAvatar(user) {
  if (user.picture) {
    const image = document.createElement("img");
    image.className = "hfnx-auth__avatar";
    image.src = user.picture;
    image.alt = "";
    image.referrerPolicy = "no-referrer";
    return image;
  }
  const letter = document.createElement("span");
  letter.className = "hfnx-auth__avatar hfnx-auth__avatar--letter";
  letter.textContent = user.username.charAt(0).toUpperCase();
  return letter;
}

function makeHfviewerAccountLink(label, path, target) {
  const link = document.createElement("a");
  link.className = "hfnx-auth__item";
  link.href = new URL(path, ACCOUNT_DESTINATION_ORIGIN).href;
  link.target = "_blank";
  link.rel = "noopener";
  link.textContent = label;
  link.setAttribute("role", "menuitem");
  link.dataset.accountDestination = target;
  link.dataset.accountDestinationReady = "0";
  accountDestinationLinks.push(link);
  link.addEventListener("click", () => {
    trackAuthEvent("space_hfviewer_account_destination_opened", { target });
    // The clicked handoff is single-use. Mint its replacement after the
    // browser has captured this anchor's current href for native navigation.
    link.dataset.accountDestinationReady = "0";
    window.setTimeout(() => { void prepareAccountDestination(link); }, 0);
  });
  return link;
}

function liveSpaceSession() {
  const session = oauthResult?.spaceSession;
  const expiresAt = Number(session?.expiresAt || 0) * 1000;
  if (!session?.id || !session?.secret || !expiresAt || expiresAt <= Date.now()) {
    return null;
  }
  return session;
}

async function prepareAccountDestination(link) {
  const session = liveSpaceSession();
  const destination = String(link?.dataset?.accountDestination || "");
  if (!session || !destination || link.dataset.accountDestinationPreparing === "1") return;
  link.dataset.accountDestinationPreparing = "1";
  try {
    const result = await postJson(DESTINATION_URL, {
      link_session_id: session.id,
      link_session_secret: session.secret,
      destination,
    });
    const loginUrl = new URL(String(result?.login_url || ""));
    if (
      !["hfviewer.com", "www.hfviewer.com"].includes(loginUrl.hostname) ||
      loginUrl.protocol !== "https:" ||
      loginUrl.pathname !== "/api/hf_space_oauth/enter"
    ) throw new Error("The account handoff URL is invalid");
    link.href = loginUrl.toString();
    link.dataset.accountDestinationReady = "1";
  } catch (error) {
    console.warn("Hugging Face Space account handoff preparation failed", error);
    link.dataset.accountDestinationReady = "0";
    trackAuthEvent("space_hf_login_failed", {
      component: "space_account_destination",
      failure_stage: "destination_prepare",
      destination,
      error_name: String(error?.name || "Error").slice(0, 80),
    });
  } finally {
    link.dataset.accountDestinationPreparing = "0";
  }
}

function prepareAccountDestinations() {
  if (!liveSpaceSession()) {
    if (oauthResult) {
      oauthResult = null;
      writeStoredResult(null);
      renderAuth();
      void prepareLogin();
    }
    return;
  }
  for (const link of accountDestinationLinks) void prepareAccountDestination(link);
}

function makeLoggedOutControl() {
  const link = document.createElement("a");
  link.dataset.spaceNativeAuth = "login";
  link.className = "space-native-auth-login";
  link.textContent = activeFlow ? "Signing in…" : "Log in";
  link.title = activeFlow
    ? "Cancel this sign-in and try again"
    : "Sign in with Hugging Face";
  link.href = preparedFlow?.loginUrl || "#";
  link.target = "_blank";
  link.rel = "noopener";
  link.setAttribute("aria-disabled", preparedFlow || activeFlow ? "false" : "true");
  link.addEventListener("click", (event) => {
    if (activeFlow) {
      event.preventDefault();
      failLogin(new Error("Sign-in cancelled"), "handoff_cancelled");
      return;
    }
    if (!preparedFlow) {
      event.preventDefault();
      void prepareLogin();
      return;
    }
    startLogin(preparedFlow, link);
  });
  return link;
}

function closeNativeLoginPopover() {
  const popover = nativeLoginPopover;
  nativeLoginPopover = null;
  if (!popover) return;
  window.removeEventListener("resize", popover.reposition);
  window.removeEventListener("scroll", popover.reposition, true);
  document.removeEventListener("pointerdown", popover.onPointerDown, true);
  document.removeEventListener("keydown", popover.onKeyDown, true);
  popover.element.remove();
}

function positionNativeLoginPopover() {
  const popover = nativeLoginPopover;
  if (!popover?.anchor?.isConnected) {
    closeNativeLoginPopover();
    return;
  }
  const rect = popover.anchor.getBoundingClientRect();
  const width = popover.element.offsetWidth || 320;
  const margin = 12;
  const left = Math.max(
    margin,
    Math.min(rect.left + rect.width / 2 - width / 2, window.innerWidth - width - margin)
  );
  popover.element.style.left = `${Math.round(left + window.scrollX)}px`;
  popover.element.style.top = `${Math.round(rect.bottom + window.scrollY + 10)}px`;
}

function requestNativeLogin(
  anchor,
  {
    title = "Sign in with Hugging Face",
    description = "Continue to use this feature in the Space.",
    intent = "protected_action",
  } = {}
) {
  if (userFromResult(oauthResult) && liveSpaceSession()) return false;
  if (!anchor?.isConnected) return false;
  closeNativeLoginPopover();
  const element = document.createElement("div");
  element.className = "hf-watch-popover hf-login-popover space-native-login-popover";
  element.setAttribute("role", "dialog");
  element.setAttribute("aria-label", title);
  const close = document.createElement("button");
  close.type = "button";
  close.className = "hf-watch-popover__close";
  close.setAttribute("aria-label", "Close");
  close.textContent = "×";
  const titleElement = document.createElement("p");
  titleElement.className = "hf-watch-popover__title";
  titleElement.textContent = title;
  const descriptionElement = document.createElement("p");
  descriptionElement.className = "hf-watch-popover__sub";
  descriptionElement.textContent = description;
  const continueLink = document.createElement("a");
  continueLink.className = "hf-login-popover__btn";
  continueLink.target = "_blank";
  continueLink.rel = "noopener";
  continueLink.setAttribute("aria-disabled", "true");
  continueLink.innerHTML =
    '<img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" alt="" width="22" height="20">' +
    '<span>Preparing sign in…</span>';
  element.append(close, titleElement, descriptionElement, continueLink);
  document.body.appendChild(element);
  const popover = {
    element,
    anchor,
    intent,
    continueLink,
    reposition: () => positionNativeLoginPopover(),
    onPointerDown: (event) => {
      if (!element.contains(event.target) && !anchor.contains(event.target)) {
        closeNativeLoginPopover();
      }
    },
    onKeyDown: (event) => {
      if (event.key === "Escape") closeNativeLoginPopover();
    },
  };
  nativeLoginPopover = popover;
  close.addEventListener("click", closeNativeLoginPopover);
  continueLink.addEventListener("click", (event) => {
    if (!preparedFlow || activeFlow) {
      event.preventDefault();
      if (!activeFlow) void prepareLogin().then(() => refreshNativeLoginPopover());
      return;
    }
    trackAuthEvent("space_hf_login_continue_clicked", {
      component: "space_native_login_popover",
      login_intent: intent,
    });
    startLogin(preparedFlow, continueLink);
  });
  window.addEventListener("resize", popover.reposition);
  window.addEventListener("scroll", popover.reposition, true);
  document.addEventListener("pointerdown", popover.onPointerDown, true);
  document.addEventListener("keydown", popover.onKeyDown, true);
  positionNativeLoginPopover();
  trackAuthEvent("space_hf_login_preflight_shown", {
    component: "space_native_login_popover",
    login_intent: intent,
  });
  void prepareLogin().then(() => refreshNativeLoginPopover());
  return true;
}

function refreshNativeLoginPopover() {
  const popover = nativeLoginPopover;
  if (!popover) return;
  if (preparedFlow?.loginUrl && !activeFlow) {
    popover.continueLink.href = preparedFlow.loginUrl;
    popover.continueLink.setAttribute("aria-disabled", "false");
    const label = popover.continueLink.querySelector("span");
    if (label) label.textContent = "Continue with Hugging Face";
  }
  positionNativeLoginPopover();
}

function makeLoggedInControl(user, { compact = false } = {}) {
  const wrap = document.createElement("div");
  wrap.dataset.spaceNativeAuth = "profile";
  wrap.className = "space-native-auth-wrap";
  if (compact) wrap.classList.add("space-native-auth-wrap--compact");

  const chip = document.createElement("button");
  chip.type = "button";
  chip.className = "hfnx-auth__chip";
  chip.setAttribute("aria-haspopup", "menu");
  chip.setAttribute("aria-expanded", "false");
  chip.appendChild(makeAvatar(user));
  const label = document.createElement("span");
  label.textContent = user.username;
  chip.appendChild(label);

  const menu = document.createElement("div");
  menu.className = "hfnx-auth__menu space-native-auth-menu";
  menu.setAttribute("role", "menu");

  const myModels = makeHfviewerAccountLink(
    "My models",
    "/?my_models=1&blogs_with_graphs=1&next_landing=1",
    "my_models"
  );
  const bookmarks = makeHfviewerAccountLink(
    "Bookmarks",
    "/?bookmarks=1&blogs_with_graphs=1&next_landing=1",
    "bookmarks"
  );
  const releaseWatchlist = makeHfviewerAccountLink(
    "Release watchlist",
    "/?release_watchlist=1&blogs_with_graphs=1&next_landing=1",
    "release_watchlist"
  );
  const writeArticle = makeHfviewerAccountLink(
    "Write article",
    "/?article_picker=1&login_intent=interactive_articles&blogs_with_graphs=1&next_landing=1",
    "write_article"
  );

  const logout = document.createElement("button");
  logout.type = "button";
  logout.className = "hfnx-auth__item";
  logout.textContent = "Log out";
  logout.setAttribute("role", "menuitem");
  logout.addEventListener("click", () => {
    trackAuthEvent("space_hf_logout");
    oauthResult = null;
    writeStoredResult(null);
    renderAuth();
    // Logged-in page loads intentionally do not prepare an OAuth flow. Once
    // the profile is cleared, prepare one immediately so the replacement Log
    // in control does not remain disabled until it is clicked or the periodic
    // refresh runs.
    void prepareLogin();
  });

  const setOpen = (open) => {
    menu.classList.toggle("is-open", open);
    chip.setAttribute("aria-expanded", open ? "true" : "false");
  };
  chip.addEventListener("click", (event) => {
    event.stopPropagation();
    setOpen(!menu.classList.contains("is-open"));
  });
  document.addEventListener("click", () => setOpen(false));

  menu.append(myModels, bookmarks, releaseWatchlist, writeArticle, logout);
  wrap.append(chip, menu);
  return wrap;
}

function renderAuth() {
  if ((!authHost && !compactAuthHost) || rendering) return;
  rendering = true;
  accountDestinationLinks = [];
  const pills = keepReleasePills();
  const user = userFromResult(oauthResult);
  if (authHost) {
    authHost.replaceChildren(...pills, user ? makeLoggedInControl(user) : makeLoggedOutControl());
  }
  if (compactAuthHost) {
    compactAuthHost.replaceChildren();
    compactAuthHost.hidden = !user;
    if (user) compactAuthHost.appendChild(makeLoggedInControl(user, { compact: true }));
  }
  queueMicrotask(() => {
    rendering = false;
    prepareAccountDestinations();
    announceAuthState();
  });
}

function applyOauthResult(callbackResult, source) {
  oauthResult = callbackResult;
  writeStoredResult(callbackResult);
  activeFlow = null;
  renderAuth();
  closeNativeLoginPopover();
  const user = userFromResult(callbackResult);
  identifyAuthenticatedUser(user, source);
  trackAuthEvent("space_hf_login_completed", {
    component: "space_nav",
    username_present: !!user?.username,
    subject_present: !!user?.subject,
    email_present: !!user?.email,
  });
}

function failLogin(error, failureStage) {
  console.warn("Hugging Face Space login failed", error);
  activeFlow = null;
  renderAuth();
  trackAuthEvent("space_hf_login_failed", {
    component: "space_nav",
    failure_stage: failureStage,
    error_name: String(error?.name || "Error").slice(0, 80),
  });
  void prepareLogin();
}

async function postJson(url, body) {
  const response = await fetch(url, {
    method: "POST",
    mode: "cors",
    credentials: "omit",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok && response.status !== 202) {
    throw new Error(payload?.error || `Request failed (${response.status})`);
  }
  return payload;
}

function announceAuthState() {
  const user = userFromResult(oauthResult);
  const session = liveSpaceSession();
  const identity = user && session ? `${user.subject || user.username}:${session.id}` : "";
  if (identity === lastAnnouncedAuthIdentity) return;
  lastAnnouncedAuthIdentity = identity;
  window.dispatchEvent(
    new CustomEvent(AUTH_CHANGED_EVENT, {
      detail: {
        authenticated: !!identity,
        username: user?.username || "",
      },
    })
  );
}

async function postAuthenticatedSpaceJson(url, payload) {
  const session = liveSpaceSession();
  if (!session) throw new Error("The Space login expired. Please sign in again.");
  try {
    return await postJson(url, {
      ...(payload || {}),
      link_session_id: session.id,
      link_session_secret: session.secret,
    });
  } catch (error) {
    if (/login expired|session expired|invalid|unauthorized/i.test(String(error?.message || ""))) {
      oauthResult = null;
      writeStoredResult(null);
      renderAuth();
      void prepareLogin();
    }
    throw error;
  }
}

window.hfviewerSpaceAuth = Object.freeze({
  isAuthenticated: () => !!userFromResult(oauthResult) && !!liveSpaceSession(),
  postJson: postAuthenticatedSpaceJson,
  requestLogin: requestNativeLogin,
});

async function pollForCompletion(flow) {
  while (activeFlow === flow && Date.now() - flow.startedAt < FLOW_TIMEOUT_MS) {
    try {
      const result = await postJson(CONSUME_URL, {
        flow_id: flow.id,
        flow_secret: flow.secret,
      });
      if (result?.status === "complete" && userFromResult(result)) {
        applyOauthResult(
          { userInfo: result.userInfo, spaceSession: result.spaceSession },
          "hf_space_native_oauth_handoff"
        );
        return;
      }
    } catch (error) {
      failLogin(error, "handoff_consume");
      return;
    }
    await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
  }
  if (activeFlow === flow) failLogin(new Error("OAuth flow timed out"), "handoff_timeout");
}

function startLogin(flow, link) {
  flow.startedAt = Date.now();
  activeFlow = flow;
  preparedFlow = null;
  // Keep the clicked anchor alive until the browser has performed its native
  // target=_blank navigation. Replacing it synchronously can cancel the popup.
  link.textContent = "Signing in…";
  link.title = "Cancel this sign-in and try again";
  link.setAttribute("aria-disabled", "false");
  trackAuthEvent("space_hf_login_clicked", { component: "space_nav" });
  void pollForCompletion(flow);
}

async function prepareLogin() {
  if (oauthResult || activeFlow) return;
  if (
    preparedFlow &&
    Date.now() - preparedFlow.preparedAt < PREPARE_REFRESH_MS
  ) return;
  if (preparePromise) return preparePromise;
  const flow = {
    id: randomFlowValue(),
    secret: randomFlowValue(),
    preparedAt: Date.now(),
    startedAt: 0,
    loginUrl: "",
  };
  preparePromise = postJson(START_URL, {
    flow_id: flow.id,
    flow_secret: flow.secret,
  }).then((result) => {
    const loginUrl = new URL(String(result?.login_url || ""));
    if (
      loginUrl.origin !== "https://huggingface.co" ||
      loginUrl.pathname !== "/oauth/authorize"
    ) throw new Error("The OAuth login URL is invalid");
    flow.loginUrl = loginUrl.toString();
    preparedFlow = flow;
    if (!activeFlow) renderAuth();
    refreshNativeLoginPopover();
  }).catch((error) => {
    console.warn("Hugging Face Space login preparation failed", error);
    trackAuthEvent("space_hf_login_failed", {
      component: "space_nav",
      failure_stage: "login_prepare",
      error_name: String(error?.name || "Error").slice(0, 80),
    });
  }).finally(() => {
    preparePromise = null;
  });
  return preparePromise;
}

async function initializeApp() {
  renderAuth();
  identifyAuthenticatedUser(userFromResult(oauthResult), "hf_space_native_oauth_restored");
  await prepareLogin();
}

if (authHost) {
  const observer = new MutationObserver(() => {
    if (!rendering && !authHost.querySelector("[data-space-native-auth]")) renderAuth();
  });
  observer.observe(authHost, { childList: true });
}

window.addEventListener("storage", (event) => {
  if (event.key !== STORAGE_KEY) return;
  oauthResult = readStoredResult();
  renderAuth();
});

window.setInterval(() => {
  void prepareLogin();
  prepareAccountDestinations();
}, PREPARE_REFRESH_MS);
void initializeApp();