-
Notifications
You must be signed in to change notification settings - Fork 413
✨ Introduce oauthLogin function #433
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 9 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
65bbab4
✨ Introduce oauthLogin function
coyotte508 4b19a14
🏷️
coyotte508 d542dc5
Merge branch 'main' into oauthLogin
coyotte508 89404fb
✅ Ignore doc-build-test repo
coyotte508 48c458d
🐛 Await createApiError
coyotte508 79200d0
♻️ Do not open new window for static space + use state for redirect url
coyotte508 7bf1885
♻️ Store state in JSON
coyotte508 655403a
🐛 Fix code challenge
coyotte508 dbf0327
📝 Document oauth
coyotte508 98240c4
Update packages/hub/README.md
coyotte508 0f09a44
💡 Comment oauthHandleRedirect and oauthHandleRedirectIfPresent
coyotte508 fb39d95
♻️ Improve API
coyotte508 9fe3416
🐛 Use randomUUID util
coyotte508 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,203 @@ | ||
import { HUB_URL } from "../consts"; | ||
import { createApiError } from "../error"; | ||
|
||
export interface OAuthResult { | ||
accessToken: string; | ||
accessTokenExpiresAt: Date; | ||
userInfo: { | ||
id: string; | ||
name: string; | ||
fullname: string; | ||
email?: string; | ||
emailVerified?: boolean; | ||
avatarUrl: string; | ||
websiteUrl?: string; | ||
isPro: boolean; | ||
orgs: Array<{ | ||
name: string; | ||
isEnterprise: boolean; | ||
}>; | ||
}; | ||
/** | ||
* State passed to the OAuth provider in the original request to the OAuth provider. | ||
*/ | ||
state?: string; | ||
/** | ||
* Granted scope | ||
*/ | ||
scope: string; | ||
} | ||
|
||
/** | ||
* To call after the OAuth provider redirects back to the app. | ||
*/ | ||
export async function oauthHandleRedirect(opts?: { hubUrl?: string }): Promise<OAuthResult> { | ||
if (typeof window === "undefined") { | ||
throw new Error("oauthHandleRedirect is only available in the browser"); | ||
} | ||
|
||
const searchParams = new URLSearchParams(window.location.search); | ||
|
||
const [error, errorDescription] = [searchParams.get("error"), searchParams.get("error_description")]; | ||
|
||
if (error) { | ||
throw new Error(`${error}: ${errorDescription}`); | ||
} | ||
|
||
const code = searchParams.get("code"); | ||
const nonce = localStorage.getItem("huggingface.co:oauth:nonce"); | ||
|
||
if (!code) { | ||
throw new Error("Missing oauth code from query parameters in redirected URL"); | ||
} | ||
|
||
if (!nonce) { | ||
throw new Error("Missing oauth nonce from localStorage"); | ||
} | ||
|
||
const codeVerifier = localStorage.getItem("huggingface.co:oauth:code_verifier"); | ||
|
||
if (!codeVerifier) { | ||
throw new Error("Missing oauth code_verifier from localStorage"); | ||
} | ||
|
||
const state = searchParams.get("state"); | ||
|
||
if (!state) { | ||
throw new Error("Missing oauth state from query parameters in redirected URL"); | ||
} | ||
|
||
let parsedState: { nonce: string; redirectUri: string; state?: string }; | ||
|
||
try { | ||
parsedState = JSON.parse(state); | ||
} catch { | ||
throw new Error("Invalid oauth state in redirected URL, unable to parse JSON: " + state); | ||
} | ||
|
||
if (parsedState.nonce !== nonce) { | ||
throw new Error("Invalid oauth state in redirected URL"); | ||
} | ||
|
||
const hubUrl = opts?.hubUrl || HUB_URL; | ||
|
||
const openidConfigUrl = `${new URL(hubUrl).origin}/.well-known/openid-configuration`; | ||
const openidConfigRes = await fetch(openidConfigUrl, { | ||
headers: { | ||
Accept: "application/json", | ||
}, | ||
}); | ||
|
||
if (!openidConfigRes.ok) { | ||
throw await createApiError(openidConfigRes); | ||
} | ||
|
||
const opendidConfig: { | ||
authorization_endpoint: string; | ||
token_endpoint: string; | ||
userinfo_endpoint: string; | ||
} = await openidConfigRes.json(); | ||
|
||
const tokenRes = await fetch(opendidConfig.token_endpoint, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/x-www-form-urlencoded", | ||
}, | ||
body: new URLSearchParams({ | ||
grant_type: "authorization_code", | ||
code, | ||
redirect_uri: parsedState.redirectUri, | ||
code_verifier: codeVerifier, | ||
}).toString(), | ||
}); | ||
|
||
localStorage.removeItem("huggingface.co:oauth:code_verifier"); | ||
localStorage.removeItem("huggingface.co:oauth:nonce"); | ||
|
||
if (!tokenRes.ok) { | ||
throw await createApiError(tokenRes); | ||
} | ||
|
||
const token: { | ||
access_token: string; | ||
expires_in: number; | ||
id_token: string; | ||
// refresh_token: string; | ||
scope: string; | ||
token_type: string; | ||
} = await tokenRes.json(); | ||
|
||
const accessTokenExpiresAt = new Date(Date.now() + token.expires_in * 1000); | ||
|
||
const userInfoRes = await fetch(opendidConfig.userinfo_endpoint, { | ||
headers: { | ||
Authorization: `Bearer ${token.access_token}`, | ||
}, | ||
}); | ||
|
||
if (!userInfoRes.ok) { | ||
throw await createApiError(userInfoRes); | ||
} | ||
|
||
const userInfo: { | ||
sub: string; | ||
name: string; | ||
preferred_username: string; | ||
email_verified?: boolean; | ||
email?: string; | ||
picture: string; | ||
website?: string; | ||
isPro: boolean; | ||
orgs?: Array<{ | ||
name: string; | ||
isEnterprise: boolean; | ||
}>; | ||
} = await userInfoRes.json(); | ||
|
||
return { | ||
accessToken: token.access_token, | ||
accessTokenExpiresAt, | ||
userInfo: { | ||
id: userInfo.sub, | ||
name: userInfo.name, | ||
fullname: userInfo.preferred_username, | ||
email: userInfo.email, | ||
emailVerified: userInfo.email_verified, | ||
avatarUrl: userInfo.picture, | ||
websiteUrl: userInfo.website, | ||
isPro: userInfo.isPro, | ||
orgs: userInfo.orgs || [], | ||
}, | ||
state: parsedState.state, | ||
scope: token.scope, | ||
}; | ||
} | ||
|
||
// if (code && !nonce) { | ||
// console.warn("Missing oauth nonce from localStorage"); | ||
// } | ||
|
||
export async function oauthHandleRedirectIfPresent(opts?: { hubUrl?: string }): Promise<OAuthResult | false> { | ||
coyotte508 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (typeof window === "undefined") { | ||
throw new Error("oauthHandleRedirect is only available in the browser"); | ||
} | ||
|
||
const searchParams = new URLSearchParams(window.location.search); | ||
|
||
if (searchParams.has("error")) { | ||
return oauthHandleRedirect(opts); | ||
} | ||
|
||
if (searchParams.has("code")) { | ||
if (!localStorage.getItem("huggingface.co:oauth:nonce")) { | ||
console.warn( | ||
"Missing oauth nonce from localStorage. This can happen when the user refreshes the page after logging in, without changing the URL." | ||
); | ||
return false; | ||
} | ||
|
||
return oauthHandleRedirect(opts); | ||
} | ||
|
||
return false; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import { base64FromBytes } from "../../../shared/src"; | ||
import { HUB_URL } from "../consts"; | ||
import { createApiError } from "../error"; | ||
|
||
/** | ||
* Use "Sign in with Hub" to authenticate a user, and get oauth user info / access token. | ||
* | ||
* - First, call `oauthLogin` to trigger the redirect to huggingface.co | ||
* - Then, after the redirect, call `oauthHandleRedirect` to get the oauth user info / access token | ||
* | ||
* There is also `oauthHandleRedirectIfPresent`, which will call `oauthHandleRedirect` if the URL contains an oauth code. | ||
* | ||
* When called from inside a static Space with OAuth enabled, it will load the config from the space. | ||
* | ||
* (Theoretically, this function could be used to authenticate a user for any OAuth provider supporting PKCE and OpenID Connect by changing `hubUrl`, | ||
* but it is currently only tested with the Hugging Face Hub.) | ||
*/ | ||
export async function oauthLogin(opts?: { | ||
/** | ||
* OAuth client ID. | ||
* | ||
* For static Spaces, you can omit this and it will be loaded from the Space config, as long as `hf_oauth: true` is present in the README.md's metadata. | ||
* For other Spaces, it is available to the backend in the OAUTH_CLIENT_ID environment variable, as long as `hf_oauth: true` is present in the README.md's metadata. | ||
* | ||
* You can also create a Developer Application at https://huggingface.co/settings/connected-applications and use its client ID. | ||
*/ | ||
clientId?: string; | ||
hubUrl?: string; | ||
/** | ||
* OAuth scope, a list of space separate scopes. | ||
* | ||
* For static Spaces, you can omit this and it will be loaded from the Space config, as long as `hf_oauth: true` is present in the README.md's metadata. | ||
* For other Spaces, it is available to the backend in the OAUTH_SCOPES environment variable, as long as `hf_oauth: true` is present in the README.md's metadata. | ||
* | ||
* Defaults to "openid profile". | ||
* | ||
* You can also create a Developer Application at https://huggingface.co/settings/connected-applications and use its scopes. | ||
* | ||
* See https://huggingface.co/docs/hub/oauth for a list of available scopes. | ||
*/ | ||
scopes?: string; | ||
/** | ||
* Redirect URI, defaults to the current URL. | ||
* | ||
* For Spaces, any URL within the Space is allowed. | ||
* | ||
* For Developer Applications, you can add any URL you want to the list of allowed redirect URIs at https://huggingface.co/settings/connected-applications. | ||
*/ | ||
redirectUri?: string; | ||
/** | ||
* State to pass to the OAuth provider, which will be returned in the call to `oauthLogin` after the redirect. | ||
*/ | ||
state?: string; | ||
}): Promise<void> { | ||
if (typeof window === "undefined") { | ||
throw new Error("oauthLogin is only available in the browser"); | ||
} | ||
|
||
const hubUrl = opts?.hubUrl || HUB_URL; | ||
const openidConfigUrl = `${new URL(hubUrl).origin}/.well-known/openid-configuration`; | ||
const openidConfigRes = await fetch(openidConfigUrl, { | ||
headers: { | ||
Accept: "application/json", | ||
}, | ||
}); | ||
|
||
if (!openidConfigRes.ok) { | ||
throw await createApiError(openidConfigRes); | ||
} | ||
|
||
const opendidConfig: { | ||
authorization_endpoint: string; | ||
token_endpoint: string; | ||
userinfo_endpoint: string; | ||
} = await openidConfigRes.json(); | ||
|
||
const newNonce = crypto.randomUUID(); | ||
// Two random UUIDs concatenated together, because min length is 43 and max length is 128 | ||
const newCodeVerifier = crypto.randomUUID() + crypto.randomUUID(); | ||
|
||
localStorage.setItem("huggingface.co:oauth:nonce", newNonce); | ||
localStorage.setItem("huggingface.co:oauth:code_verifier", newCodeVerifier); | ||
|
||
const redirectUri = opts?.redirectUri || window.location.href; | ||
const state = JSON.stringify({ | ||
nonce: newNonce, | ||
redirectUri, | ||
state: opts?.state, | ||
}); | ||
|
||
// @ts-expect-error window.huggingface is defined inside static Spaces. | ||
const variables: Record<string, string> | null = window?.huggingface?.variables ?? null; | ||
|
||
const clientId = opts?.clientId || variables?.OAUTH_CLIENT_ID; | ||
|
||
if (!clientId) { | ||
if (variables) { | ||
throw new Error("Missing clientId, please add hf_oauth: true to the README.md's metadata in your static Space"); | ||
} | ||
throw new Error("Missing clientId"); | ||
} | ||
|
||
const challenge = base64FromBytes( | ||
new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(newCodeVerifier))) | ||
) | ||
.replace(/[+]/g, "-") | ||
.replace(/[/]/g, "_") | ||
.replace(/=/g, ""); | ||
|
||
window.location.href = `${opendidConfig.authorization_endpoint}?${new URLSearchParams({ | ||
coyotte508 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
client_id: clientId, | ||
scope: opts?.scopes || "openid profile", | ||
response_type: "code", | ||
redirect_uri: redirectUri, | ||
state, | ||
code_challenge: challenge, | ||
code_challenge_method: "S256", | ||
}).toString()}`; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.