|
| 1 | +import { HUB_URL } from "../consts"; |
| 2 | +import { createApiError } from "../error"; |
| 3 | + |
| 4 | +export interface OAuthResult { |
| 5 | + accessToken: string; |
| 6 | + accessTokenExpiresAt: Date; |
| 7 | + userInfo: { |
| 8 | + id: string; |
| 9 | + name: string; |
| 10 | + fullname: string; |
| 11 | + email?: string; |
| 12 | + emailVerified?: boolean; |
| 13 | + avatarUrl: string; |
| 14 | + websiteUrl?: string; |
| 15 | + isPro: boolean; |
| 16 | + orgs: Array<{ |
| 17 | + name: string; |
| 18 | + isEnterprise: boolean; |
| 19 | + }>; |
| 20 | + }; |
| 21 | + /** |
| 22 | + * State passed to the OAuth provider in the original request to the OAuth provider. |
| 23 | + */ |
| 24 | + state?: string; |
| 25 | + /** |
| 26 | + * Granted scope |
| 27 | + */ |
| 28 | + scope: string; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * To call after the OAuth provider redirects back to the app. |
| 33 | + * |
| 34 | + * There is also a helper function {@link oauthHandleRedirectIfPresent}, which will call `oauthHandleRedirect` if the URL contains an oauth code |
| 35 | + * in the query parameters and return `false` otherwise. |
| 36 | + */ |
| 37 | +export async function oauthHandleRedirect(opts?: { hubUrl?: string }): Promise<OAuthResult> { |
| 38 | + if (typeof window === "undefined") { |
| 39 | + throw new Error("oauthHandleRedirect is only available in the browser"); |
| 40 | + } |
| 41 | + |
| 42 | + const searchParams = new URLSearchParams(window.location.search); |
| 43 | + |
| 44 | + const [error, errorDescription] = [searchParams.get("error"), searchParams.get("error_description")]; |
| 45 | + |
| 46 | + if (error) { |
| 47 | + throw new Error(`${error}: ${errorDescription}`); |
| 48 | + } |
| 49 | + |
| 50 | + const code = searchParams.get("code"); |
| 51 | + const nonce = localStorage.getItem("huggingface.co:oauth:nonce"); |
| 52 | + |
| 53 | + if (!code) { |
| 54 | + throw new Error("Missing oauth code from query parameters in redirected URL"); |
| 55 | + } |
| 56 | + |
| 57 | + if (!nonce) { |
| 58 | + throw new Error("Missing oauth nonce from localStorage"); |
| 59 | + } |
| 60 | + |
| 61 | + const codeVerifier = localStorage.getItem("huggingface.co:oauth:code_verifier"); |
| 62 | + |
| 63 | + if (!codeVerifier) { |
| 64 | + throw new Error("Missing oauth code_verifier from localStorage"); |
| 65 | + } |
| 66 | + |
| 67 | + const state = searchParams.get("state"); |
| 68 | + |
| 69 | + if (!state) { |
| 70 | + throw new Error("Missing oauth state from query parameters in redirected URL"); |
| 71 | + } |
| 72 | + |
| 73 | + let parsedState: { nonce: string; redirectUri: string; state?: string }; |
| 74 | + |
| 75 | + try { |
| 76 | + parsedState = JSON.parse(state); |
| 77 | + } catch { |
| 78 | + throw new Error("Invalid oauth state in redirected URL, unable to parse JSON: " + state); |
| 79 | + } |
| 80 | + |
| 81 | + if (parsedState.nonce !== nonce) { |
| 82 | + throw new Error("Invalid oauth state in redirected URL"); |
| 83 | + } |
| 84 | + |
| 85 | + const hubUrl = opts?.hubUrl || HUB_URL; |
| 86 | + |
| 87 | + const openidConfigUrl = `${new URL(hubUrl).origin}/.well-known/openid-configuration`; |
| 88 | + const openidConfigRes = await fetch(openidConfigUrl, { |
| 89 | + headers: { |
| 90 | + Accept: "application/json", |
| 91 | + }, |
| 92 | + }); |
| 93 | + |
| 94 | + if (!openidConfigRes.ok) { |
| 95 | + throw await createApiError(openidConfigRes); |
| 96 | + } |
| 97 | + |
| 98 | + const opendidConfig: { |
| 99 | + authorization_endpoint: string; |
| 100 | + token_endpoint: string; |
| 101 | + userinfo_endpoint: string; |
| 102 | + } = await openidConfigRes.json(); |
| 103 | + |
| 104 | + const tokenRes = await fetch(opendidConfig.token_endpoint, { |
| 105 | + method: "POST", |
| 106 | + headers: { |
| 107 | + "Content-Type": "application/x-www-form-urlencoded", |
| 108 | + }, |
| 109 | + body: new URLSearchParams({ |
| 110 | + grant_type: "authorization_code", |
| 111 | + code, |
| 112 | + redirect_uri: parsedState.redirectUri, |
| 113 | + code_verifier: codeVerifier, |
| 114 | + }).toString(), |
| 115 | + }); |
| 116 | + |
| 117 | + localStorage.removeItem("huggingface.co:oauth:code_verifier"); |
| 118 | + localStorage.removeItem("huggingface.co:oauth:nonce"); |
| 119 | + |
| 120 | + if (!tokenRes.ok) { |
| 121 | + throw await createApiError(tokenRes); |
| 122 | + } |
| 123 | + |
| 124 | + const token: { |
| 125 | + access_token: string; |
| 126 | + expires_in: number; |
| 127 | + id_token: string; |
| 128 | + // refresh_token: string; |
| 129 | + scope: string; |
| 130 | + token_type: string; |
| 131 | + } = await tokenRes.json(); |
| 132 | + |
| 133 | + const accessTokenExpiresAt = new Date(Date.now() + token.expires_in * 1000); |
| 134 | + |
| 135 | + const userInfoRes = await fetch(opendidConfig.userinfo_endpoint, { |
| 136 | + headers: { |
| 137 | + Authorization: `Bearer ${token.access_token}`, |
| 138 | + }, |
| 139 | + }); |
| 140 | + |
| 141 | + if (!userInfoRes.ok) { |
| 142 | + throw await createApiError(userInfoRes); |
| 143 | + } |
| 144 | + |
| 145 | + const userInfo: { |
| 146 | + sub: string; |
| 147 | + name: string; |
| 148 | + preferred_username: string; |
| 149 | + email_verified?: boolean; |
| 150 | + email?: string; |
| 151 | + picture: string; |
| 152 | + website?: string; |
| 153 | + isPro: boolean; |
| 154 | + orgs?: Array<{ |
| 155 | + name: string; |
| 156 | + isEnterprise: boolean; |
| 157 | + }>; |
| 158 | + } = await userInfoRes.json(); |
| 159 | + |
| 160 | + return { |
| 161 | + accessToken: token.access_token, |
| 162 | + accessTokenExpiresAt, |
| 163 | + userInfo: { |
| 164 | + id: userInfo.sub, |
| 165 | + name: userInfo.name, |
| 166 | + fullname: userInfo.preferred_username, |
| 167 | + email: userInfo.email, |
| 168 | + emailVerified: userInfo.email_verified, |
| 169 | + avatarUrl: userInfo.picture, |
| 170 | + websiteUrl: userInfo.website, |
| 171 | + isPro: userInfo.isPro, |
| 172 | + orgs: userInfo.orgs || [], |
| 173 | + }, |
| 174 | + state: parsedState.state, |
| 175 | + scope: token.scope, |
| 176 | + }; |
| 177 | +} |
| 178 | + |
| 179 | +// if (code && !nonce) { |
| 180 | +// console.warn("Missing oauth nonce from localStorage"); |
| 181 | +// } |
| 182 | + |
| 183 | +/** |
| 184 | + * To call after the OAuth provider redirects back to the app. |
| 185 | + * |
| 186 | + * It returns false if the URL does not contain an oauth code in the query parameters, otherwise |
| 187 | + * it calls {@link oauthHandleRedirect}. |
| 188 | + * |
| 189 | + * Depending on your app, you may want to call {@link oauthHandleRedirect} directly instead. |
| 190 | + */ |
| 191 | +export async function oauthHandleRedirectIfPresent(opts?: { hubUrl?: string }): Promise<OAuthResult | false> { |
| 192 | + if (typeof window === "undefined") { |
| 193 | + throw new Error("oauthHandleRedirect is only available in the browser"); |
| 194 | + } |
| 195 | + |
| 196 | + const searchParams = new URLSearchParams(window.location.search); |
| 197 | + |
| 198 | + if (searchParams.has("error")) { |
| 199 | + return oauthHandleRedirect(opts); |
| 200 | + } |
| 201 | + |
| 202 | + if (searchParams.has("code")) { |
| 203 | + if (!localStorage.getItem("huggingface.co:oauth:nonce")) { |
| 204 | + console.warn( |
| 205 | + "Missing oauth nonce from localStorage. This can happen when the user refreshes the page after logging in, without changing the URL." |
| 206 | + ); |
| 207 | + return false; |
| 208 | + } |
| 209 | + |
| 210 | + return oauthHandleRedirect(opts); |
| 211 | + } |
| 212 | + |
| 213 | + return false; |
| 214 | +} |
0 commit comments