File size: 4,441 Bytes
1cce69a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a6d00
 
 
1cce69a
 
 
 
c6a6d00
 
 
 
1cce69a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a6d00
 
 
 
 
 
 
 
 
 
 
 
 
 
1cce69a
 
c6a6d00
1cce69a
 
c6a6d00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cce69a
 
 
 
c6a6d00
 
 
1cce69a
 
 
c6a6d00
 
 
 
 
 
 
 
 
1cce69a
 
 
c6a6d00
 
 
 
 
1cce69a
c6a6d00
1cce69a
 
 
 
 
 
 
 
 
 
 
 
 
c6a6d00
 
 
 
 
 
 
 
1cce69a
 
 
 
 
 
 
 
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
"use client";

import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  useCallback,
} from "react";
import {
  oauthLoginUrl,
  oauthHandleRedirectIfPresent,
  type OAuthResult,
} from "@huggingface/hub";
import { AUTH_STORAGE_KEY } from "@/utils/auth";

interface OAuthAppConfig {
  clientId: string;
  scopes: string;
}

interface AuthContextValue {
  oauth: OAuthResult | null;
  // Whether OAuth is configured for this deployment. Determined by hitting
  // /api/auth/config — the server reads OAUTH_CLIENT_ID from its env, which
  // HF Spaces injects when `hf_oauth: true` is set in the README. When
  // unconfigured, the button hides itself.
  isAuthAvailable: boolean;
  signIn: () => Promise<void>;
  signOut: () => void;
}

const AuthContext = createContext<AuthContextValue>({
  oauth: null,
  isAuthAvailable: false,
  signIn: async () => {},
  signOut: () => {},
});

// Mirror the access token into an HttpOnly cookie so the same-origin
// /api/proxy route can attach it to <video> requests, which can't carry an
// Authorization header from JS.
async function setSessionCookie(accessToken: string): Promise<void> {
  try {
    await fetch("/api/auth/session", {
      method: "POST",
      headers: { Authorization: `Bearer ${accessToken}` },
    });
  } catch (err) {
    console.error("Failed to set session cookie", err);
  }
}

async function clearSessionCookie(): Promise<void> {
  try {
    await fetch("/api/auth/session", { method: "DELETE" });
  } catch (err) {
    console.error("Failed to clear session cookie", err);
  }
}

function isExpired(result: OAuthResult): boolean {
  const exp = result.accessTokenExpiresAt;
  if (!exp) return false;
  const expDate = exp instanceof Date ? exp : new Date(exp);
  return expDate.getTime() <= Date.now();
}

async function fetchOAuthConfig(): Promise<OAuthAppConfig | null> {
  try {
    const res = await fetch("/api/auth/config");
    if (!res.ok) return null;
    const data = (await res.json()) as
      | { enabled: false }
      | { enabled: true; clientId: string; scopes: string };
    if (!data.enabled) return null;
    return { clientId: data.clientId, scopes: data.scopes };
  } catch {
    return null;
  }
}

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [oauth, setOauth] = useState<OAuthResult | null>(null);
  const [config, setConfig] = useState<OAuthAppConfig | null>(null);

  useEffect(() => {
    let cancelled = false;

    fetchOAuthConfig().then((cfg) => {
      if (cancelled || !cfg) return;
      setConfig(cfg);

      const stored = window.localStorage.getItem(AUTH_STORAGE_KEY);
      if (stored) {
        try {
          const parsed = JSON.parse(stored) as OAuthResult;
          if (isExpired(parsed)) {
            window.localStorage.removeItem(AUTH_STORAGE_KEY);
            clearSessionCookie();
          } else {
            setOauth(parsed);
            setSessionCookie(parsed.accessToken);
            return;
          }
        } catch {
          window.localStorage.removeItem(AUTH_STORAGE_KEY);
        }
      }

      oauthHandleRedirectIfPresent()
        .then((result) => {
          if (cancelled || !result) return;
          window.localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(result));
          setOauth(result);
          setSessionCookie(result.accessToken);
        })
        .catch((err) => {
          console.error("OAuth redirect handling failed", err);
        });
    });

    return () => {
      cancelled = true;
    };
  }, []);

  const signIn = useCallback(async () => {
    if (!config) return;
    const url = await oauthLoginUrl({
      clientId: config.clientId,
      scopes: config.scopes,
    });
    window.location.href = url + "&prompt=consent";
  }, [config]);

  const signOut = useCallback(() => {
    window.localStorage.removeItem(AUTH_STORAGE_KEY);
    setOauth(null);
    clearSessionCookie();
    // Strip ?code=... left in the URL by the OAuth redirect, if any.
    const cleanUrl = window.location.href.replace(/\?.*$/, "");
    if (cleanUrl !== window.location.href) {
      window.history.replaceState(null, "", cleanUrl);
    }
  }, []);

  return (
    <AuthContext.Provider
      value={{
        oauth,
        isAuthAvailable: !!config,
        signIn,
        signOut,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}