-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthHashCompletion.tsx
More file actions
200 lines (176 loc) · 5.98 KB
/
AuthHashCompletion.tsx
File metadata and controls
200 lines (176 loc) · 5.98 KB
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
"use client";
import { useEffect } from "react";
import {
getDefaultNextPathByType,
isSupportedEmailAuthType,
normaliseNextPath,
} from "@/utils/authRedirects";
const INVALID_LINK_MESSAGE =
"Hmm, that sign-in link is invalid or has expired. Please request a new one.";
const isAuthDebugEnabled = process.env.NEXT_PUBLIC_AUTH_DEBUG === "true";
const debugAuth = (event: string, data?: Record<string, unknown>) => {
if (!isAuthDebugEnabled) return;
console.log("[auth-hash-completion]", event, data ?? {});
};
const redirectToSignIn = (nextPath: string) => {
const signInUrl = new URL("/sign-in", window.location.origin);
signInUrl.searchParams.set("error", INVALID_LINK_MESSAGE);
signInUrl.searchParams.set("redirect_to", nextPath);
window.location.assign(signInUrl.toString());
};
export default function AuthHashCompletion() {
useEffect(() => {
const queryParams = new URLSearchParams(window.location.search);
const hash = window.location.hash;
const hashParams = hash.startsWith("#")
? new URLSearchParams(hash.slice(1))
: new URLSearchParams();
const hashType = hashParams.get("type");
const preferredNextPath =
queryParams.get("next") ?? queryParams.get("redirect_to");
const requestedType = queryParams.get("type") ?? hashType;
const defaultNextPath = getDefaultNextPathByType(requestedType);
const nextPath = normaliseNextPath(preferredNextPath, defaultNextPath);
const authCode = queryParams.get("code");
const hasAuthHashPayload =
hash.startsWith("#") &&
(hashParams.get("access_token") ||
hashParams.get("refresh_token") ||
hashParams.get("error") ||
hashParams.get("error_description"));
// Dashboard-generated links often land at `/` first. Move immediately to a
// lightweight completion page to avoid rendering homepage content before
// auth finalization redirects.
if (
window.location.pathname === "/" &&
(authCode || Boolean(hasAuthHashPayload))
) {
const completeUrl = new URL("/auth/complete", window.location.origin);
const completeParams = new URLSearchParams(window.location.search);
if (!completeParams.get("next")) {
completeParams.set("next", nextPath);
}
if (!completeParams.get("type") && requestedType) {
completeParams.set("type", requestedType);
}
completeUrl.search = completeParams.toString();
completeUrl.hash = window.location.hash;
debugAuth("reroute-to-complete-page", {
nextPath,
path: window.location.pathname,
});
window.location.replace(completeUrl.toString());
return;
}
if (authCode) {
debugAuth("detected-pkce-code", {
nextPath,
path: window.location.pathname,
});
const callbackUrl = new URL("/auth/callback", window.location.origin);
callbackUrl.searchParams.set("code", authCode);
callbackUrl.searchParams.set("next", nextPath);
if (requestedType) {
callbackUrl.searchParams.set("type", requestedType);
}
window.location.assign(callbackUrl.toString());
return;
}
if (!hash.startsWith("#")) {
return;
}
const accessToken = hashParams.get("access_token");
const refreshToken = hashParams.get("refresh_token");
const type = hashParams.get("type");
const tokenType = hashParams.get("token_type");
const hashError = hashParams.get("error");
const hashErrorDescription = hashParams.get("error_description");
if (hashError || hashErrorDescription) {
debugAuth("hash-auth-error", {
code: hashError ?? null,
reason: hashErrorDescription ?? null,
nextPath,
});
// Remove auth hash before redirecting away.
window.history.replaceState(
window.history.state,
"",
`${window.location.pathname}${window.location.search}`
);
redirectToSignIn(nextPath);
return;
}
if (
!accessToken ||
!refreshToken ||
!type ||
!tokenType ||
tokenType.toLowerCase() !== "bearer" ||
!isSupportedEmailAuthType(type)
) {
return;
}
const typedNextPath = normaliseNextPath(
preferredNextPath,
getDefaultNextPathByType(type)
);
// Remove sensitive hash tokens from the address bar as soon as possible.
window.history.replaceState(
window.history.state,
"",
`${window.location.pathname}${window.location.search}`
);
debugAuth("detected-hash-auth", {
type,
nextPath: typedNextPath,
path: window.location.pathname,
});
const finalizeSessionFromHash = async () => {
try {
const response = await fetch("/auth/session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin",
body: JSON.stringify({
access_token: accessToken,
refresh_token: refreshToken,
type,
next: typedNextPath,
}),
});
const data = (await response.json()) as {
ok?: boolean;
next?: string;
error?: string;
};
if (!response.ok || !data.ok) {
debugAuth("session-finalization-failed", {
status: response.status,
reason: data?.error ?? "unknown",
type,
nextPath: typedNextPath,
});
redirectToSignIn(typedNextPath);
return;
}
const resolvedNextPath = normaliseNextPath(data.next, typedNextPath);
debugAuth("session-finalized", {
type,
nextPath: resolvedNextPath,
});
window.location.assign(resolvedNextPath);
} catch (error) {
debugAuth("session-finalization-error", {
type,
nextPath: typedNextPath,
reason: error instanceof Error ? error.message : "unknown",
});
redirectToSignIn(typedNextPath);
}
};
void finalizeSessionFromHash();
}, []);
return null;
}