forked from koshikraj/ottopus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe-next.ts
More file actions
31 lines (27 loc) · 1.26 KB
/
Copy pathsafe-next.ts
File metadata and controls
31 lines (27 loc) · 1.26 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
/** Where to land when the `next` parameter is missing or refuses to be trusted. */
export const DEFAULT_NEXT = '/portfolio'
/**
* Narrows a `?next=` parameter to somewhere inside this app.
*
* The value arrives in a URL anyone can write and hand to someone else, and it
* ends up in `router.replace`. Next.js will navigate to a `javascript:` URL
* given one, so an unchecked value is script execution on our origin, not just
* an open redirect.
*
* The rule is narrow on purpose: a single leading slash, then a path. That
* rejects every scheme without having to enumerate them, and it rejects the
* two spellings of "protocol-relative" — `//evil.example`, and `/\evil.example`
* which several browsers normalise to the same thing.
*
* Anything else silently becomes the default. There is no legitimate way to
* arrive here with an off-site destination, so there is nothing to explain.
*/
export function safeNext(raw: string | null | undefined, fallback = DEFAULT_NEXT): string {
if (!raw) return fallback
// A tab or newline inside the value can split it past a naive check, and no
// real path contains one.
if (/[ -\s]/.test(raw)) return fallback
if (raw[0] !== '/') return fallback
if (raw[1] === '/' || raw[1] === '\\') return fallback
return raw
}