-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathutils.ts
More file actions
82 lines (71 loc) · 2.35 KB
/
Copy pathutils.ts
File metadata and controls
82 lines (71 loc) · 2.35 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
const DEFAULT_REDIRECT = "/";
// Pathnames that are NOT user-navigable destinations: fetcher endpoints,
// OAuth/auth callbacks, JSON APIs, the magic-link redemption route, and the
// auth flow routes themselves (which would create a redirect loop). Note
// `/admin/api/` covers admin JSON endpoints while leaving `/admin`,
// `/admin/back-office/*`, `/admin/orgs`, etc. navigable.
const NON_NAVIGABLE_PREFIXES = ["/resources/", "/auth/", "/admin/api/", "/api/", "/engine/"];
const NON_NAVIGABLE_EXACT = new Set([
"/magic",
"/logout",
"/login",
"/login/magic",
"/login/mfa",
"/login/sso",
]);
function isNavigablePath(pathname: string): boolean {
if (NON_NAVIGABLE_EXACT.has(pathname)) return false;
return !NON_NAVIGABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
/**
* This should be used any time the redirect path is user-provided
* (Like the query string on our login/signup pages). This avoids
* open-redirect vulnerabilities and prevents redirecting users to
* non-page routes (e.g. fetcher endpoints) that would render blank.
* @param {string} path The redirect destination
* @param {string} defaultRedirect The redirect to use if the to is unsafe.
*/
export function sanitizeRedirectPath(
path: string | undefined | null,
defaultRedirect: string = DEFAULT_REDIRECT
): string {
if (!path || typeof path !== "string") {
return defaultRedirect;
}
const pathnameEnd = path.search(/[?#]/);
const rawPathname = pathnameEnd === -1 ? path : path.slice(0, pathnameEnd);
if (!path.startsWith("/") || path.startsWith("//") || rawPathname.includes("\\")) {
return defaultRedirect;
}
try {
// should not parse as a full URL
new URL(path);
return defaultRedirect;
} catch {}
let parsed: URL;
try {
// ensure it's a valid relative path
parsed = new URL(path, "https://example.com");
if (parsed.hostname !== "example.com") {
return defaultRedirect;
}
} catch {
return defaultRedirect;
}
if (!isNavigablePath(parsed.pathname)) {
return defaultRedirect;
}
return path;
}
export function titleCase(original: string): string {
return original
.split(" ")
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(" ");
}
export function appEnvTitleTag(appEnv?: string): string {
if (!appEnv || appEnv === "production") {
return "";
}
return ` (${appEnv})`;
}