Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

oauthCallback.ts

34 lines1.3 KB

1/**
2 * The address an OAuth sign-in sent the browser back to, as the user pasted it,
3 * if it answers this sign-in: the redirect's own address, its one state, and
4 * one code or one error. Throws otherwise.
5 */
6export function oauthCallbackUrl(value: string, redirectUri: string, state: string) {
7 const expected = new URL(redirectUri);
8 const callback = pastedUrl(value, expected.protocol);
9 const states = callback.searchParams.getAll("state");
10 const codes = callback.searchParams.getAll("code");
11 const errors = callback.searchParams.getAll("error");
12 if (
13 value.length > 16_384 ||
14 callback.origin !== expected.origin ||
15 callback.pathname !== expected.pathname ||
16 callback.username ||
17 callback.password ||
18 callback.hash ||
19 states.length !== 1 ||
20 states[0] !== state ||
21 !(
22 (codes.length === 1 && Boolean(codes[0]) && errors.length === 0) ||
23 (errors.length === 1 && Boolean(errors[0]) && codes.length === 0)
24 )
25 )
26 throw new Error("This redirect URL does not belong to the current sign-in.");
27 return callback;
29​
30/** A URL copied from an address bar, which can hide its `http://`. Throws if it isn't one. */
31export function pastedUrl(value: string, protocol = "http:") {
32 const pasted = value.trim();
33 return new URL(/^[a-z][a-z\d+.-]*:\/\//iu.test(pasted) ? pasted : `${protocol}//${pasted}`);