All files / src/lib redirect.ts

100% Statements 3/3
100% Branches 9/9
100% Functions 1/1
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      15x                 12x   3x    
// Where to go after a step such as /welcome: a path in this app taken from
// the address bar, so it must never lead to another site.
 
/**
 * `target` if it is a path in this app, otherwise `/`. Rejects other
 * origins (`https://…`), protocol-relative (`//evil.example`) and backslash
 * (`/\evil.example`, which browsers read as `//`) forms, control characters
 * (URL parsers drop tabs and line breaks, so `/\t/evil.example` becomes
 * `//evil.example`) and `/welcome` itself.
 */
export function safeRedirect(target: unknown): string {
  if (
    typeof target !== 'string' ||
    !target.startsWith('/') ||
    target.startsWith('//') ||
    target.startsWith('/\\') ||
    /\p{Cc}/u.test(target) ||
    target === '/welcome' ||
    target.startsWith('/welcome?')
  ) {
    return '/'
  }
  return target
}