File size: 8,734 Bytes
21dd449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { HUB_URL } from "../consts";
import { createApiError } from "../error";

export interface UserInfo {
	/**
	 * OpenID Connect field. Unique identifier for the user, even in case of rename.
	 */
	sub: string;
	/**
	 * OpenID Connect field. The user's full name.
	 */
	name: string;
	/**
	 * OpenID Connect field. The user's username.
	 */
	preferred_username: string;
	/**
	 * OpenID Connect field, available if scope "email" was granted.
	 */
	email_verified?: boolean;
	/**
	 * OpenID Connect field, available if scope "email" was granted.
	 */
	email?: string;
	/**
	 * OpenID Connect field. The user's profile picture URL.
	 */
	picture: string;
	/**
	 * OpenID Connect field. The user's profile URL.
	 */
	profile: string;
	/**
	 * OpenID Connect field. The user's website URL.
	 */
	website?: string;

	/**
	 * Hugging Face field. Whether the user is a pro user.
	 */
	isPro: boolean;
	/**
	 * Hugging Face field. Whether the user has a payment method set up. Needs "read-billing" scope.
	 */
	canPay?: boolean;
	/**
	 * Hugging Face field. The user's orgs
	 */
	orgs?: Array<{
		/**
		 * OpenID Connect field. Unique identifier for the org.
		 */
		sub: string;
		/**
		 * OpenID Connect field. The org's full name.
		 */
		name: string;
		/**
		 * OpenID Connect field. The org's username.
		 */
		preferred_username: string;
		/**
		 * OpenID Connect field. The org's profile picture URL.
		 */
		picture: string;

		/**
		 * Hugging Face field. Whether the org is an enterprise org.
		 */
		isEnterprise: boolean;
		/**
		 * Hugging Face field. Whether the org has a payment method set up. Needs "read-billing" scope, and the user needs to approve access to the org in the OAuth page.
		 */
		canPay?: boolean;
		/**
		 * Hugging Face field. The user's role in the org. The user needs to approve access to the org in the OAuth page.
		 */
		roleInOrg?: string;
		/**
		 * HuggingFace field. When the user granted the oauth app access to the org, but didn't complete SSO.
		 *
		 * Should never happen directly after the oauth flow.
		 */
		pendingSSO?: boolean;
		/**
		 * HuggingFace field. When the user granted the oauth app access to the org, but didn't complete MFA.
		 *
		 * Should never happen directly after the oauth flow.
		 */
		missingMFA?: boolean;
	}>;
}

export interface OAuthResult {
	accessToken: string;
	accessTokenExpiresAt: Date;
	userInfo: UserInfo;
	/**
	 * 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.
 *
 * There is also a helper function {@link oauthHandleRedirectIfPresent}, which will call `oauthHandleRedirect` if the URL contains an oauth code
 * in the query parameters and return `false` otherwise.
 */
export async function oauthHandleRedirect(opts?: {
	/**
	 * The URL of the hub. Defaults to {@link HUB_URL}.
	 */
	hubUrl?: string;
	/**
	 * The URL to analyze.
	 *
	 * @default window.location.href
	 */
	redirectedUrl?: string;
	/**
	 * nonce generated by oauthLoginUrl
	 *
	 * @default localStorage.getItem("huggingface.co:oauth:nonce")
	 */
	nonce?: string;
	/**
	 * codeVerifier generated by oauthLoginUrl
	 *
	 * @default localStorage.getItem("huggingface.co:oauth:code_verifier")
	 */
	codeVerifier?: string;
}): Promise<OAuthResult> {
	if (typeof window === "undefined" && !opts?.redirectedUrl) {
		throw new Error("oauthHandleRedirect is only available in the browser, unless you provide redirectedUrl");
	}
	if (typeof localStorage === "undefined" && (!opts?.nonce || !opts?.codeVerifier)) {
		throw new Error(
			"oauthHandleRedirect requires localStorage to be available, unless you provide nonce and codeVerifier"
		);
	}

	const redirectedUrl = opts?.redirectedUrl ?? window.location.href;
	const searchParams = (() => {
		try {
			return new URL(redirectedUrl).searchParams;
		} catch (err) {
			throw new Error("Failed to parse redirected URL: " + redirectedUrl);
		}
	})();

	const [error, errorDescription] = [searchParams.get("error"), searchParams.get("error_description")];

	if (error) {
		throw new Error(`${error}: ${errorDescription}`);
	}

	const code = searchParams.get("code");
	const nonce = opts?.nonce ?? localStorage.getItem("huggingface.co:oauth:nonce");

	if (!code) {
		throw new Error("Missing oauth code from query parameters in redirected URL: " + redirectedUrl);
	}

	if (!nonce) {
		throw new Error("Missing oauth nonce from localStorage");
	}

	const codeVerifier = opts?.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 openidConfig: {
		authorization_endpoint: string;
		token_endpoint: string;
		userinfo_endpoint: string;
	} = await openidConfigRes.json();

	const tokenRes = await fetch(openidConfig.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(),
	});

	if (!opts?.codeVerifier) {
		localStorage.removeItem("huggingface.co:oauth:code_verifier");
	}
	if (!opts?.nonce) {
		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(openidConfig.userinfo_endpoint, {
		headers: {
			Authorization: `Bearer ${token.access_token}`,
		},
	});

	if (!userInfoRes.ok) {
		throw await createApiError(userInfoRes);
	}

	const userInfo: UserInfo = await userInfoRes.json();

	return {
		accessToken: token.access_token,
		accessTokenExpiresAt,
		userInfo: userInfo,
		state: parsedState.state,
		scope: token.scope,
	};
}

// if (code && !nonce) {
//   console.warn("Missing oauth nonce from localStorage");
// }

/**
 * To call after the OAuth provider redirects back to the app.
 *
 * It returns false if the URL does not contain an oauth code in the query parameters, otherwise
 * it calls {@link oauthHandleRedirect}.
 *
 * Depending on your app, you may want to call {@link oauthHandleRedirect} directly instead.
 */
export async function oauthHandleRedirectIfPresent(opts?: {
	/**
	 * The URL of the hub. Defaults to {@link HUB_URL}.
	 */
	hubUrl?: string;
	/**
	 * The URL to analyze.
	 *
	 * @default window.location.href
	 */
	redirectedUrl?: string;
	/**
	 * nonce generated by oauthLoginUrl
	 *
	 * @default localStorage.getItem("huggingface.co:oauth:nonce")
	 */
	nonce?: string;
	/**
	 * codeVerifier generated by oauthLoginUrl
	 *
	 * @default localStorage.getItem("huggingface.co:oauth:code_verifier")
	 */
	codeVerifier?: string;
}): Promise<OAuthResult | false> {
	if (typeof window === "undefined" && !opts?.redirectedUrl) {
		throw new Error("oauthHandleRedirect is only available in the browser, unless you provide redirectedUrl");
	}
	if (typeof localStorage === "undefined" && (!opts?.nonce || !opts?.codeVerifier)) {
		throw new Error(
			"oauthHandleRedirect requires localStorage to be available, unless you provide nonce and codeVerifier"
		);
	}
	const searchParams = new URLSearchParams(opts?.redirectedUrl ?? 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;
}