Skip to main content
Security guideReviewed

Open redirect vulnerability: send people only to your own pages

An open redirect sends a visitor wherever a link tells it to, under your domain name.

This guide explains what a return address is for, why "it starts with a slash" and "it contains our domain" both fail, how to check the parsed result or, better, an allowlist of routes, and gives you a local Node.js lab with a URL parser test table and a regression test.

Open redirect lab: parser test table, sign-in server and regression test

An illustration written for this page, not client code. A Node.js lab parses 24 return addresses with new URL() and prints what five checks decide for each, runs a sign-in and sign-out server on 127.0.0.1 in a flawed and two fixed variants with a scripted client that reads every Location header sent, and includes a regression test on the built-in test runner that fails for the flawed variant and passes for both fixed ones.

How to use it

It ends with steps to confirm the same in your own browser. It needs Node.js only and was recorded on Node.js v26.0.0 on macOS. Use it on your own machine to learn, and to test redirects you own.

open-redirects.txt

ILLUSTRATION FOR LEARNING. The sign-in flow, the three server variants, the checks and every input below were written for this page. They are not a client's code or a client's result. Run the lab on your own machine to learn, and use its table and its test on redirects you own. Do not send any of its inputs to a system you do not own or are not authorised in writing to test.

WHAT IT NEEDS
Node.js, with nothing to install. The lab uses only built-in modules, node:http, node:crypto, node:assert and node:test, with the global URL and URLSearchParams classes. The Node.js documentation marks the test runner stable from version 20.0.0. Every output below was recorded on Node.js v26.0.0, macOS 27.2.1 (arm64). It was not run on Windows or Linux, and no browser was run: the lab shows what each server sent, and the standards cited on the page say what a browser does with it.

WHAT IT TOUCHES
parser-table.mjs opens no connection at all. client.mjs and the test start one server at a time on 127.0.0.1, on a port the system picks, and stop it before they exit. The scripted client sends requests to that server only (sendToLab() refuses any other address) and never requests the address in a Location header. RFC 2606 reserves four top level DNS names, .test, .example, .invalid and .localhost, so that names under them can be used without fear of conflicts with current or future actual top level names in the global DNS. app.example and elsewhere.test sit under two of them, which is what the lab's code and output mean by reserved names. The lab uses them only as text; nothing connects to them. The account and password are made up.

THE PUBLIC ADDRESS
The server listens on 127.0.0.1 but is configured with https://app.example as its public address, the way an application behind a proxy is. It never reads its own address from the Host header. A browser signing in would have posted to https://app.example/sign-in, so the client parses each Location against that address, which is what the Fetch Standard's location URL algorithm does with a redirect.

THE CHECKS (in return-address.mjs)
  startsWithSlash    naive: accepts any value that starts with /.
  mentionsOurHost    naive: accepts any value that contains app.example.
  keepOnlyThePath    a near-fix: parses the value and keeps only its path, query and fragment.
  checkSameOrigin    fixed: refuses control characters, spaces and backslashes, parses the value against https://app.example/, accepts it only if the origin is https://app.example and it has no user name or password, and redirects to the parsed URL.
  checkRouteList     fixed and stronger: accepts only a route name or a path on an explicit list, and builds the Location from the list.

THE SERVER VARIANTS (in lab-server.mjs)
  flawed         startsWithSlash after sign-in and after sign-out.
  fixed-origin   checkSameOrigin after sign-in; the public route list after sign-out.
  fixed-routes   checkRouteList after sign-in; the public route list after sign-out.
A refused value falls back to /account after sign-in and to /signed-out after sign-out.

SET-UP
Make an empty folder, save the six files below into it under the names shown, and run the commands under RUN IT from that folder. The commands set LAB_VARIANT the way macOS and Linux shells do; on Windows, set it the way your shell does.

==== File 1 of 6: return-address.mjs ====
// return-address.mjs: the inputs the lab sends, two naive checks, a near-fix
// and the two fixed checks. Each check takes the return address a request
// carried and decides where the redirect goes. The naive checks and the
// near-fix are wrong on purpose: never copy them.

// The site's public origin. It is configured, never read from the request.
export const SITE_ORIGIN = 'https://app.example'
export const SITE_HOST = 'app.example'

// Where each flow sends people when the return address is refused.
export const AFTER_SIGN_IN = '/account'
export const AFTER_SIGN_OUT = '/signed-out'

// Route names and the paths they stand for. Pages behind sign-in first,
// then the pages a signed-out visitor can open.
export const SIGNED_IN_ROUTES = { account: '/account', orders: '/orders', billing: '/settings/billing' }
export const PUBLIC_ROUTES = { home: '/', 'signed-out': '/signed-out', 'sign-in': '/sign-in' }

// One input per class. Each value is what a handler receives, after the one
// decode the form or query string parser performs.
export const INPUTS = [
  { id: 'R1', label: 'plain relative path', value: '/account' },
  { id: 'R2', label: 'path with a query and a fragment', value: '/orders?status=open#latest' },
  { id: 'R3', label: 'relative path without a leading slash', value: 'account' },
  { id: 'R4', label: 'absolute URL to our own site', value: 'https://app.example/account' },
  { id: 'R5', label: 'absolute URL to another host', value: 'https://elsewhere.test/sign-in' },
  { id: 'R6', label: 'protocol-relative address, two slashes', value: '//elsewhere.test/sign-in' },
  { id: 'R7', label: 'three slashes', value: '///elsewhere.test/sign-in' },
  { id: 'R8', label: 'a slash, then a backslash', value: '/\\elsewhere.test/sign-in' },
  { id: 'R9', label: 'two backslashes', value: '\\\\elsewhere.test/sign-in' },
  { id: 'R10', label: 'encoded slashes', value: '/%2F%2Felsewhere.test/sign-in' },
  { id: 'R11', label: 'encoded dots', value: '/%2e%2e//elsewhere.test/sign-in' },
  { id: 'R12', label: 'same scheme, no slashes', value: 'https:elsewhere.test/sign-in' },
  { id: 'R13', label: 'other scheme, no slashes', value: 'http:elsewhere.test/sign-in' },
  { id: 'R14', label: 'our host name as a user name', value: 'https://app.example@elsewhere.test/sign-in' },
  { id: 'R15', label: 'user name trick, protocol-relative', value: '//app.example@elsewhere.test/sign-in' },
  { id: 'R16', label: 'our host name as a subdomain', value: 'https://app.example.elsewhere.test/sign-in' },
  { id: 'R17', label: 'user name on our own host', value: 'https://alex@app.example/account' },
  { id: 'R18', label: 'leading space', value: ' //elsewhere.test/sign-in' },
  { id: 'R19', label: 'tab between the slashes', value: '/\t/elsewhere.test/sign-in' },
  { id: 'R20', label: 'newline between the slashes', value: '/\n/elsewhere.test/sign-in' },
  { id: 'R21', label: 'percent-encoding in the host', value: '//elsewhere%2Etest/sign-in' },
  { id: 'R22', label: 'look-alike host (Cyrillic a)', value: 'https://\u0430pp.example/account' },
  { id: 'R23', label: 'ideographic full stop in the host', value: '//elsewhere\u3002test/sign-in' },
  { id: 'R24', label: 'javascript: scheme', value: 'javascript:alert(1)' },
]

// Naive check 1: accept anything that starts with a slash.
export function startsWithSlash(value) {
  return value.startsWith('/')
}

// Naive check 2: accept anything that mentions our host name.
export function mentionsOurHost(value) {
  return value.includes(SITE_HOST)
}

// Near-fix: parse the value, then keep only its path, query and fragment.
// Throws a TypeError when the value does not parse.
export function keepOnlyThePath(value, base) {
  const parsed = new URL(value, base)
  return parsed.pathname + parsed.search + parsed.hash
}

// Refused outright: C0 controls, space, DEL and the backslash. The URL parser
// strips some of these from the ends, removes tabs and newlines anywhere and
// reads a backslash as a slash in an http or https URL, so a value holding
// one can mean something else to the next program that reads it.
const AMBIGUOUS_CHARACTER = /[\x00-\x20\x7f\\]/

function refuse(fallbackPath, reason) {
  return { allowed: false, location: fallbackPath, reason: reason }
}

// Fixed 1: resolve the value against our own origin and accept it only if
// the result is on that origin, with no user name or password. Redirect to
// the parsed result, never to the original text.
export function checkSameOrigin(value, fallbackPath) {
  if (typeof value !== 'string' || value === '') return refuse(fallbackPath, 'empty')
  if (AMBIGUOUS_CHARACTER.test(value)) return refuse(fallbackPath, 'control character, space or backslash')
  let target
  try {
    target = new URL(value, SITE_ORIGIN + '/')
  } catch (error) {
    return refuse(fallbackPath, 'does not parse')
  }
  if (target.origin !== SITE_ORIGIN) return refuse(fallbackPath, 'origin is ' + target.origin)
  if (target.username !== '' || target.password !== '') return refuse(fallbackPath, 'carries a user name or password')
  return { allowed: true, location: target.href, reason: 'same origin' }
}

// Fixed 2: accept only a route name or a path on an explicit list, and build
// the redirect from the list. Nothing from the request reaches the header.
export function checkRouteList(value, routes, fallbackPath) {
  for (const name of Object.keys(routes)) {
    const path = routes[name]
    if (value === name || value === path) return { allowed: true, location: path, reason: 'route ' + name }
  }
  return refuse(fallbackPath, 'not on the route list')
}

// Shows invisible characters by name, so a printed value can be read.
const NAMED_CHARACTERS = { '\t': '(TAB)', '\n': '(LF)', '\r': '(CR)', ' ': '(SP)', '\u007f': '(DEL)' }

export function showValue(value) {
  let shown = ''
  for (const character of String(value)) {
    const code = character.codePointAt(0)
    if (NAMED_CHARACTERS[character]) shown += NAMED_CHARACTERS[character]
    else if (code < 0x20) shown += '(' + formatCodePoint(code) + ')'
    else shown += character
  }
  return shown
}

export function formatCodePoint(code) {
  return 'U+' + code.toString(16).toUpperCase().padStart(4, '0')
}

// Lists each character outside ASCII with its position, counting from 1.
export function listNonAscii(value) {
  const found = []
  let position = 0
  for (const character of String(value)) {
    position += 1
    const code = character.codePointAt(0)
    if (code > 0x7e) found.push(formatCodePoint(code) + ' at position ' + position)
  }
  return found
}

==== File 2 of 6: lab-server.mjs ====
// lab-server.mjs: a small sign-in and sign-out flow in three variants.
//   flawed        accepts a return address that starts with "/"
//   fixed-origin  checkSameOrigin() after sign-in
//   fixed-routes  checkRouteList() after sign-in
// After sign-out, both fixed variants accept only a public route. The server
// listens on 127.0.0.1 on a port the system picks, and is configured with
// SITE_ORIGIN as its public address, the way an application behind a proxy
// is. It never reads its address from the Host header. The account and
// password are made up for the lab.
import { randomBytes } from 'node:crypto'
import http from 'node:http'
import {
  AFTER_SIGN_IN,
  AFTER_SIGN_OUT,
  PUBLIC_ROUTES,
  SIGNED_IN_ROUTES,
  checkRouteList,
  checkSameOrigin,
  startsWithSlash,
} from './return-address.mjs'

export const VARIANTS = ['flawed', 'fixed-origin', 'fixed-routes']
export const LAB_ACCOUNT = { username: 'alex', password: 'lab-password-not-real' }

function chooseSignInLocation(variant, value) {
  if (variant === 'flawed') return startsWithSlash(value) ? value : AFTER_SIGN_IN
  if (variant === 'fixed-origin') return checkSameOrigin(value, AFTER_SIGN_IN).location
  return checkRouteList(value, SIGNED_IN_ROUTES, AFTER_SIGN_IN).location
}

function chooseSignOutLocation(variant, value) {
  if (variant === 'flawed') return startsWithSlash(value) ? value : AFTER_SIGN_OUT
  return checkRouteList(value, PUBLIC_ROUTES, AFTER_SIGN_OUT).location
}

function readSessionId(request) {
  const cookieHeader = request.headers.cookie || ''
  for (const part of cookieHeader.split(';')) {
    const pair = part.trim().split('=')
    if (pair[0] === 'session') return pair[1] || ''
  }
  return ''
}

function readForm(request) {
  return new Promise(function (resolve, reject) {
    const chunks = []
    request.on('data', function (chunk) { chunks.push(chunk) })
    request.on('end', function () { resolve(new URLSearchParams(Buffer.concat(chunks).toString('utf8'))) })
    request.on('error', reject)
  })
}

// If node:http throws while setting the Location header, the lab answers 500
// instead of crashing, so the client can show what happened.
function sendRedirect(response, location, cookie) {
  if (cookie) response.setHeader('Set-Cookie', cookie)
  try {
    response.setHeader('Location', location)
  } catch (error) {
    response.removeHeader('Set-Cookie')
    response.statusCode = 500
    response.end('node:http refused the Location header: ' + error.code)
    return
  }
  response.statusCode = 303
  response.end()
}

function showAccount(sessions, request, response) {
  if (sessions.has(readSessionId(request))) {
    response.statusCode = 200
    response.end('account page')
    return
  }
  sendRedirect(response, '/sign-in?return_to=' + encodeURIComponent('/account'))
}

async function signIn(variant, sessions, request, response) {
  const form = await readForm(request)
  const isKnown = form.get('username') === LAB_ACCOUNT.username && form.get('password') === LAB_ACCOUNT.password
  if (!isKnown) {
    response.statusCode = 401
    response.end('sign-in failed')
    return
  }
  const sessionId = randomBytes(16).toString('hex')
  sessions.set(sessionId, LAB_ACCOUNT.username)
  const cookie = 'session=' + sessionId + '; Path=/; HttpOnly; Secure; SameSite=Lax'
  sendRedirect(response, chooseSignInLocation(variant, form.get('return_to') || ''), cookie)
}

async function signOut(variant, sessions, request, response) {
  const form = await readForm(request)
  sessions.delete(readSessionId(request))
  const cookie = 'session=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax'
  sendRedirect(response, chooseSignOutLocation(variant, form.get('return_to') || ''), cookie)
}

function routeRequest(variant, sessions, request, response) {
  const path = request.url.split('?')[0]
  if (request.method === 'GET' && path === '/account') return showAccount(sessions, request, response)
  if (request.method === 'POST' && path === '/sign-in') return signIn(variant, sessions, request, response)
  if (request.method === 'POST' && path === '/sign-out') return signOut(variant, sessions, request, response)
  response.statusCode = 404
  response.end('not found')
}

export function startLabServer(variant) {
  if (!VARIANTS.includes(variant)) throw new Error('unknown variant: ' + variant)
  const sessions = new Map()
  const server = http.createServer(function (request, response) {
    routeRequest(variant, sessions, request, response)
  })
  return new Promise(function (resolve) {
    server.listen(0, '127.0.0.1', function () {
      resolve({ variant: variant, server: server, port: server.address().port })
    })
  })
}

export function stopLabServer(lab) {
  return new Promise(function (resolve) {
    lab.server.close(resolve)
    lab.server.closeAllConnections()
  })
}

==== File 3 of 6: lab-http.mjs ====
// lab-http.mjs: the scripted client's requests. It reads each response with
// node:http and never requests the address in a Location header, so each
// 303 is reported as the server sent it. Requests go to the lab server on
// 127.0.0.1 only; nothing is sent to app.example or elsewhere.test.
import http from 'node:http'
import { LAB_ACCOUNT } from './lab-server.mjs'
import { SITE_ORIGIN } from './return-address.mjs'

export function sendToLab(lab, method, path, form, cookie) {
  const target = new URL(path, 'http://127.0.0.1:' + lab.port)
  if (target.hostname !== '127.0.0.1' || target.port !== String(lab.port)) {
    throw new Error('LAB GUARD: refused a request outside the lab server')
  }
  const body = form ? new URLSearchParams(form).toString() : ''
  const headers = {}
  if (form) {
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    headers['Content-Length'] = Buffer.byteLength(body)
  }
  if (cookie) headers.Cookie = cookie
  return new Promise(function (resolve, reject) {
    const request = http.request(target, { method: method, headers: headers, agent: false }, function (response) {
      const chunks = []
      response.on('data', function (chunk) { chunks.push(chunk) })
      response.on('end', function () {
        resolve({
          status: response.statusCode,
          location: response.headers.location,
          setCookie: response.headers['set-cookie'],
          body: Buffer.concat(chunks).toString('utf8'),
        })
      })
    })
    request.on('error', reject)
    request.end(body)
  })
}

function readSessionCookie(result) {
  const cookies = result.setCookie || []
  return cookies.length ? cookies[0].split(';')[0] : ''
}

export async function signInWith(lab, returnAddress) {
  const form = { username: LAB_ACCOUNT.username, password: LAB_ACCOUNT.password, return_to: returnAddress }
  const result = await sendToLab(lab, 'POST', '/sign-in', form)
  return { status: result.status, location: result.location, body: result.body, cookie: readSessionCookie(result) }
}

export async function signOutWith(lab, cookie, returnAddress) {
  const result = await sendToLab(lab, 'POST', '/sign-out', { return_to: returnAddress }, cookie)
  return { status: result.status, location: result.location, body: result.body, setCookie: result.setCookie }
}

// What a browser does with a Location value, per the Fetch Standard's
// location URL: parse it with the URL of the response that carried it. The
// browser posted to SITE_ORIGIN + path, so that is the base.
export function resolveLocation(location, path) {
  if (location === undefined) return { text: 'no Location header', staysOnSite: false }
  let target
  try {
    target = new URL(location, SITE_ORIGIN + path)
  } catch (error) {
    return { text: 'does not parse', staysOnSite: false }
  }
  if (target.origin === SITE_ORIGIN) return { text: target.href + ': stays', staysOnSite: true }
  return { text: 'LEAVES for ' + target.origin, staysOnSite: false }
}

==== File 4 of 6: parser-table.mjs ====
// parser-table.mjs: usage: node parser-table.mjs
// Prints what new URL(input, base) reports for each input and what each
// check decides. It opens no network connection: app.example and
// elsewhere.test are reserved names, used here only as text.
import {
  AFTER_SIGN_IN,
  INPUTS,
  SIGNED_IN_ROUTES,
  SITE_HOST,
  SITE_ORIGIN,
  checkRouteList,
  checkSameOrigin,
  keepOnlyThePath,
  listNonAscii,
  mentionsOurHost,
  showValue,
  startsWithSlash,
} from './return-address.mjs'

// The address the sign-in form posts to. A browser resolves a relative
// Location against the URL of the response that carried it.
const BASE = SITE_ORIGIN + '/sign-in'

function parse(value) {
  try {
    return new URL(value, BASE)
  } catch (error) {
    return error
  }
}

// Where a Location value lands once it is parsed against BASE.
function describeLanding(location) {
  const parsed = parse(location)
  if (parsed instanceof Error) return 'does not parse (' + parsed.name + ')'
  if (parsed.origin === SITE_ORIGIN) return 'stays'
  if (parsed.origin === 'null') return 'LEAVES for a ' + parsed.protocol + ' URL (origin null)'
  return 'LEAVES for ' + parsed.origin
}

function line(name, value) {
  console.log('  ' + name.padEnd(26) + value)
}

function describeNaive(isAccepted, value) {
  if (!isAccepted) return { text: 'refuses', short: 'refused' }
  const landing = describeLanding(value)
  return { text: 'accepts: ' + landing, short: landing === 'stays' ? 'stays' : 'LEAVES' }
}

function describePathOnly(value) {
  let location
  try {
    location = keepOnlyThePath(value, BASE)
  } catch (error) {
    return { text: 'throws ' + error.name, short: 'throws' }
  }
  const landing = describeLanding(location)
  return { text: 'sends ' + showValue(location) + ': ' + landing, short: landing === 'stays' ? 'stays' : 'LEAVES' }
}

function describeFixed(decision) {
  if (!decision.allowed) return { text: 'refuses (' + decision.reason + ')', short: 'refused' }
  return { text: 'sends ' + decision.location + ': ' + describeLanding(decision.location), short: 'stays' }
}

function printParsed(value) {
  const parsed = parse(value)
  if (parsed instanceof Error) {
    line('new URL(input, base)', 'throws ' + parsed.name + ': ' + parsed.message)
    return
  }
  line('new URL(input, base)', parsed.href)
  line('origin', parsed.origin)
  if (parsed.username !== '') line('username', parsed.username)
}

function printDecodedAgain(value) {
  let decoded
  try {
    decoded = decodeURIComponent(value)
  } catch (error) {
    return
  }
  if (decoded === value) return
  const landing = describeLanding(decoded)
  const outcome = landing === 'stays' ? 'stays on ' + SITE_ORIGIN : landing
  line('decoded once more', showValue(decoded) + ': ' + outcome)
}

function printRow(input) {
  console.log(input.id + '  ' + input.label)
  line('input', showValue(input.value))
  const nonAscii = listNonAscii(input.value)
  if (nonAscii.length) line('outside ASCII', nonAscii.join(', '))
  printParsed(input.value)
  printDecodedAgain(input.value)
  const results = {
    slash: describeNaive(startsWithSlash(input.value), input.value),
    host: describeNaive(mentionsOurHost(input.value), input.value),
    path: describePathOnly(input.value),
    origin: describeFixed(checkSameOrigin(input.value, AFTER_SIGN_IN)),
    routes: describeFixed(checkRouteList(input.value, SIGNED_IN_ROUTES, AFTER_SIGN_IN)),
  }
  line('starts with "/"', results.slash.text)
  line('mentions "' + SITE_HOST + '"', results.host.text)
  line('keep only the path', results.path.text)
  line('fixed: same origin', results.origin.text)
  line('fixed: route list', results.routes.text)
  console.log('')
  return results
}

function printSummary(rows) {
  console.log('SUMMARY (refused means the check sent its fallback, ' + AFTER_SIGN_IN + ')')
  const columns = ['Row', 'starts "/"', 'mentions host', 'path only', 'same origin', 'route list']
  const widths = [5, 12, 15, 11, 13, 10]
  const pad = function (cells) {
    return cells.map(function (cell, index) { return String(cell).padEnd(widths[index]) }).join('').trimEnd()
  }
  console.log(pad(columns))
  for (const row of rows) {
    const results = row.results
    console.log(pad([row.id, results.slash.short, results.host.short, results.path.short, results.origin.short, results.routes.short]))
  }
}

console.log('OPEN REDIRECT LAB, PART A: URL PARSER TEST TABLE')
console.log('Node.js ' + process.version + ' on ' + process.platform + ' ' + process.arch)
console.log('Our site: ' + SITE_ORIGIN + '. Another host: elsewhere.test. Both are reserved names.')
console.log('Base for relative input: ' + BASE + ', the address the sign-in form posts to.')
console.log('(SP), (TAB) and (LF) stand for a space, a tab and a line feed in the value.')
console.log('')
const rows = []
for (const input of INPUTS) rows.push({ id: input.id, results: printRow(input) })
printSummary(rows)

==== File 5 of 6: client.mjs ====
// client.mjs: usage: node client.mjs
// Starts each server variant in turn, signs in and out once per input, and
// prints the status and the Location header exactly as the server sent them,
// then where that Location points once parsed against the address the
// browser posted to. It follows no redirect. Each server is stopped before
// the next one starts.
import { INPUTS, SITE_ORIGIN, showValue } from './return-address.mjs'
import { resolveLocation, sendToLab, signInWith, signOutWith } from './lab-http.mjs'
import { VARIANTS, startLabServer, stopLabServer } from './lab-server.mjs'

const DESCRIPTIONS = {
  flawed: 'accepts a return address that starts with "/", after sign-in and after sign-out',
  'fixed-origin': 'same-origin check after sign-in; public route list after sign-out',
  'fixed-routes': 'route list after sign-in; public route list after sign-out',
}

function formatStep(id, step, result, path) {
  const location = result.location === undefined ? '(none)' : showValue(result.location)
  const landing = result.status === 303 ? resolveLocation(result.location, path).text : 'not a redirect: ' + result.body
  return (id.padEnd(5) + step.padEnd(10) + String(result.status).padEnd(8) + location.padEnd(49) + ' ' + landing).trimEnd()
}

async function printVariant(variant) {
  const lab = await startLabServer(variant)
  console.log('VARIANT ' + variant + ': ' + DESCRIPTIONS[variant])
  console.log('Listening on 127.0.0.1, port chosen by the system. Public address: ' + SITE_ORIGIN)
  const bounce = await sendToLab(lab, 'GET', '/account')
  console.log('GET /account with no session: ' + bounce.status + ', Location ' + bounce.location)
  console.log('Row  Step      Status  Location as sent                                  Parsed against the address posted to')
  let leaves = 0
  let errors = 0
  for (const input of INPUTS) {
    const signIn = await signInWith(lab, input.value)
    const signOut = await signOutWith(lab, signIn.cookie, input.value)
    console.log(formatStep(input.id, 'sign-in', signIn, '/sign-in'))
    console.log(formatStep('', 'sign-out', signOut, '/sign-out'))
    const steps = [{ result: signIn, path: '/sign-in' }, { result: signOut, path: '/sign-out' }]
    for (const step of steps) {
      if (step.result.status !== 303) errors += 1
      else if (!resolveLocation(step.result.location, step.path).staysOnSite) leaves += 1
    }
  }
  const check = await signInWith(lab, '/account')
  await signOutWith(lab, check.cookie, '/')
  const afterSignOut = await sendToLab(lab, 'GET', '/account', null, check.cookie)
  console.log('Old session cookie after sign-out, GET /account: ' + afterSignOut.status + ', Location ' + afterSignOut.location)
  console.log('Redirects that leave ' + SITE_ORIGIN + ': ' + leaves + '. Responses that were not a redirect: ' + errors + '.')
  await stopLabServer(lab)
  console.log('Server stopped.')
  console.log('')
}

console.log('OPEN REDIRECT LAB, PART B: WHAT EACH SERVER VARIANT SENT')
console.log('Node.js ' + process.version + ' on ' + process.platform + ' ' + process.arch)
console.log('')
for (const variant of VARIANTS) await printVariant(variant)

==== File 6 of 6: redirects.test.mjs ====
// redirects.test.mjs: a regression test for the variant LAB_VARIANT names:
// fixed-routes (the default), fixed-origin or flawed. Every sign-in and
// sign-out must answer 303 with a Location that, parsed against the address
// the browser posted to, stays on SITE_ORIGIN. It passes for both fixed
// variants and fails for the flawed one.
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { INPUTS, SITE_ORIGIN, showValue } from './return-address.mjs'
import { sendToLab, signInWith, signOutWith } from './lab-http.mjs'
import { startLabServer, stopLabServer } from './lab-server.mjs'

const variant = process.env.LAB_VARIANT || 'fixed-routes'
let lab

before(async function () { lab = await startLabServer(variant) })
after(async function () { await stopLabServer(lab) })

function assertStaysOnSite(result, path) {
  assert.equal(result.status, 303, variant + ' answered ' + result.status + ' instead of a redirect')
  const target = new URL(result.location, SITE_ORIGIN + path)
  assert.equal(target.origin, SITE_ORIGIN, variant + ' sent Location ' + showValue(result.location))
}

for (const input of INPUTS) {
  test(input.id + ' ' + input.label + ': sign-in and sign-out stay on ' + SITE_ORIGIN, async function () {
    const signIn = await signInWith(lab, input.value)
    assertStaysOnSite(signIn, '/sign-in')
    const signOut = await signOutWith(lab, signIn.cookie, input.value)
    assertStaysOnSite(signOut, '/sign-out')
  })
}

test('R1 is honoured: /account after sign-in lands on /account', async function () {
  const signIn = await signInWith(lab, '/account')
  assert.equal(new URL(signIn.location, SITE_ORIGIN + '/sign-in').href, SITE_ORIGIN + '/account')
})

test('after sign-out, the old session cookie no longer opens /account', async function () {
  const signIn = await signInWith(lab, '/account')
  await signOutWith(lab, signIn.cookie, '/')
  const result = await sendToLab(lab, 'GET', '/account', null, signIn.cookie)
  assert.equal(result.status, 303)
  assert.equal(new URL(result.location, SITE_ORIGIN + '/account').pathname, '/sign-in')
})

==== RUN IT ====
node parser-table.mjs
node client.mjs
node --test redirects.test.mjs
LAB_VARIANT=fixed-origin node --test redirects.test.mjs
LAB_VARIANT=flawed node --test redirects.test.mjs

==== OUTPUT OF node parser-table.mjs (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
OPEN REDIRECT LAB, PART A: URL PARSER TEST TABLE
Node.js v26.0.0 on darwin arm64
Our site: https://app.example. Another host: elsewhere.test. Both are reserved names.
Base for relative input: https://app.example/sign-in, the address the sign-in form posts to.
(SP), (TAB) and (LF) stand for a space, a tab and a line feed in the value.

R1  plain relative path
  input                     /account
  new URL(input, base)      https://app.example/account
  origin                    https://app.example
  starts with "/"           accepts: stays
  mentions "app.example"    refuses
  keep only the path        sends /account: stays
  fixed: same origin        sends https://app.example/account: stays
  fixed: route list         sends /account: stays

R2  path with a query and a fragment
  input                     /orders?status=open#latest
  new URL(input, base)      https://app.example/orders?status=open#latest
  origin                    https://app.example
  starts with "/"           accepts: stays
  mentions "app.example"    refuses
  keep only the path        sends /orders?status=open#latest: stays
  fixed: same origin        sends https://app.example/orders?status=open#latest: stays
  fixed: route list         refuses (not on the route list)

R3  relative path without a leading slash
  input                     account
  new URL(input, base)      https://app.example/account
  origin                    https://app.example
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /account: stays
  fixed: same origin        sends https://app.example/account: stays
  fixed: route list         sends /account: stays

R4  absolute URL to our own site
  input                     https://app.example/account
  new URL(input, base)      https://app.example/account
  origin                    https://app.example
  starts with "/"           refuses
  mentions "app.example"    accepts: stays
  keep only the path        sends /account: stays
  fixed: same origin        sends https://app.example/account: stays
  fixed: route list         refuses (not on the route list)

R5  absolute URL to another host
  input                     https://elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R6  protocol-relative address, two slashes
  input                     //elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R7  three slashes
  input                     ///elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R8  a slash, then a backslash
  input                     /\elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (control character, space or backslash)
  fixed: route list         refuses (not on the route list)

R9  two backslashes
  input                     \\elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (control character, space or backslash)
  fixed: route list         refuses (not on the route list)

R10  encoded slashes
  input                     /%2F%2Felsewhere.test/sign-in
  new URL(input, base)      https://app.example/%2F%2Felsewhere.test/sign-in
  origin                    https://app.example
  decoded once more         ///elsewhere.test/sign-in: LEAVES for https://elsewhere.test
  starts with "/"           accepts: stays
  mentions "app.example"    refuses
  keep only the path        sends /%2F%2Felsewhere.test/sign-in: stays
  fixed: same origin        sends https://app.example/%2F%2Felsewhere.test/sign-in: stays
  fixed: route list         refuses (not on the route list)

R11  encoded dots
  input                     /%2e%2e//elsewhere.test/sign-in
  new URL(input, base)      https://app.example//elsewhere.test/sign-in
  origin                    https://app.example
  decoded once more         /..//elsewhere.test/sign-in: stays on https://app.example
  starts with "/"           accepts: stays
  mentions "app.example"    refuses
  keep only the path        sends //elsewhere.test/sign-in: LEAVES for https://elsewhere.test
  fixed: same origin        sends https://app.example//elsewhere.test/sign-in: stays
  fixed: route list         refuses (not on the route list)

R12  same scheme, no slashes
  input                     https:elsewhere.test/sign-in
  new URL(input, base)      https://app.example/elsewhere.test/sign-in
  origin                    https://app.example
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /elsewhere.test/sign-in: stays
  fixed: same origin        sends https://app.example/elsewhere.test/sign-in: stays
  fixed: route list         refuses (not on the route list)

R13  other scheme, no slashes
  input                     http:elsewhere.test/sign-in
  new URL(input, base)      http://elsewhere.test/sign-in
  origin                    http://elsewhere.test
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is http://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R14  our host name as a user name
  input                     https://app.example@elsewhere.test/sign-in
  new URL(input, base)      https://app.example@elsewhere.test/sign-in
  origin                    https://elsewhere.test
  username                  app.example
  starts with "/"           refuses
  mentions "app.example"    accepts: LEAVES for https://elsewhere.test
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R15  user name trick, protocol-relative
  input                     //app.example@elsewhere.test/sign-in
  new URL(input, base)      https://app.example@elsewhere.test/sign-in
  origin                    https://elsewhere.test
  username                  app.example
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    accepts: LEAVES for https://elsewhere.test
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R16  our host name as a subdomain
  input                     https://app.example.elsewhere.test/sign-in
  new URL(input, base)      https://app.example.elsewhere.test/sign-in
  origin                    https://app.example.elsewhere.test
  starts with "/"           refuses
  mentions "app.example"    accepts: LEAVES for https://app.example.elsewhere.test
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://app.example.elsewhere.test)
  fixed: route list         refuses (not on the route list)

R17  user name on our own host
  input                     https://alex@app.example/account
  new URL(input, base)      https://alex@app.example/account
  origin                    https://app.example
  username                  alex
  starts with "/"           refuses
  mentions "app.example"    accepts: stays
  keep only the path        sends /account: stays
  fixed: same origin        refuses (carries a user name or password)
  fixed: route list         refuses (not on the route list)

R18  leading space
  input                     (SP)//elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (control character, space or backslash)
  fixed: route list         refuses (not on the route list)

R19  tab between the slashes
  input                     /(TAB)/elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (control character, space or backslash)
  fixed: route list         refuses (not on the route list)

R20  newline between the slashes
  input                     /(LF)/elsewhere.test/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (control character, space or backslash)
  fixed: route list         refuses (not on the route list)

R21  percent-encoding in the host
  input                     //elsewhere%2Etest/sign-in
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  decoded once more         //elsewhere.test/sign-in: LEAVES for https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R22  look-alike host (Cyrillic a)
  input                     https://аpp.example/account
  outside ASCII             U+0430 at position 9
  new URL(input, base)      https://xn--pp-6kc.example/account
  origin                    https://xn--pp-6kc.example
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends /account: stays
  fixed: same origin        refuses (origin is https://xn--pp-6kc.example)
  fixed: route list         refuses (not on the route list)

R23  ideographic full stop in the host
  input                     //elsewhere。test/sign-in
  outside ASCII             U+3002 at position 12
  new URL(input, base)      https://elsewhere.test/sign-in
  origin                    https://elsewhere.test
  starts with "/"           accepts: LEAVES for https://elsewhere.test
  mentions "app.example"    refuses
  keep only the path        sends /sign-in: stays
  fixed: same origin        refuses (origin is https://elsewhere.test)
  fixed: route list         refuses (not on the route list)

R24  javascript: scheme
  input                     javascript:alert(1)
  new URL(input, base)      javascript:alert(1)
  origin                    null
  starts with "/"           refuses
  mentions "app.example"    refuses
  keep only the path        sends alert(1): stays
  fixed: same origin        refuses (origin is null)
  fixed: route list         refuses (not on the route list)

SUMMARY (refused means the check sent its fallback, /account)
Row  starts "/"  mentions host  path only  same origin  route list
R1   stays       refused        stays      stays        stays
R2   stays       refused        stays      stays        refused
R3   refused     refused        stays      stays        stays
R4   refused     stays          stays      stays        refused
R5   refused     refused        stays      refused      refused
R6   LEAVES      refused        stays      refused      refused
R7   LEAVES      refused        stays      refused      refused
R8   LEAVES      refused        stays      refused      refused
R9   refused     refused        stays      refused      refused
R10  stays       refused        stays      stays        refused
R11  stays       refused        LEAVES     stays        refused
R12  refused     refused        stays      stays        refused
R13  refused     refused        stays      refused      refused
R14  refused     LEAVES         stays      refused      refused
R15  LEAVES      LEAVES         stays      refused      refused
R16  refused     LEAVES         stays      refused      refused
R17  refused     stays          stays      refused      refused
R18  refused     refused        stays      refused      refused
R19  LEAVES      refused        stays      refused      refused
R20  LEAVES      refused        stays      refused      refused
R21  LEAVES      refused        stays      refused      refused
R22  refused     refused        stays      refused      refused
R23  LEAVES      refused        stays      refused      refused
R24  refused     refused        stays      refused      refused
exit code: 0

==== OUTPUT OF node client.mjs (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
OPEN REDIRECT LAB, PART B: WHAT EACH SERVER VARIANT SENT
Node.js v26.0.0 on darwin arm64

VARIANT flawed: accepts a return address that starts with "/", after sign-in and after sign-out
Listening on 127.0.0.1, port chosen by the system. Public address: https://app.example
GET /account with no session: 303, Location /sign-in?return_to=%2Faccount
Row  Step      Status  Location as sent                                  Parsed against the address posted to
R1   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /account                                          https://app.example/account: stays
R2   sign-in   303     /orders?status=open#latest                        https://app.example/orders?status=open#latest: stays
     sign-out  303     /orders?status=open#latest                        https://app.example/orders?status=open#latest: stays
R3   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R4   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R5   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R6   sign-in   303     //elsewhere.test/sign-in                          LEAVES for https://elsewhere.test
     sign-out  303     //elsewhere.test/sign-in                          LEAVES for https://elsewhere.test
R7   sign-in   303     ///elsewhere.test/sign-in                         LEAVES for https://elsewhere.test
     sign-out  303     ///elsewhere.test/sign-in                         LEAVES for https://elsewhere.test
R8   sign-in   303     /\elsewhere.test/sign-in                          LEAVES for https://elsewhere.test
     sign-out  303     /\elsewhere.test/sign-in                          LEAVES for https://elsewhere.test
R9   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R10  sign-in   303     /%2F%2Felsewhere.test/sign-in                     https://app.example/%2F%2Felsewhere.test/sign-in: stays
     sign-out  303     /%2F%2Felsewhere.test/sign-in                     https://app.example/%2F%2Felsewhere.test/sign-in: stays
R11  sign-in   303     /%2e%2e//elsewhere.test/sign-in                   https://app.example//elsewhere.test/sign-in: stays
     sign-out  303     /%2e%2e//elsewhere.test/sign-in                   https://app.example//elsewhere.test/sign-in: stays
R12  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R13  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R14  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R15  sign-in   303     //app.example@elsewhere.test/sign-in              LEAVES for https://elsewhere.test
     sign-out  303     //app.example@elsewhere.test/sign-in              LEAVES for https://elsewhere.test
R16  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R17  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R18  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R19  sign-in   303     /(TAB)/elsewhere.test/sign-in                     LEAVES for https://elsewhere.test
     sign-out  303     /(TAB)/elsewhere.test/sign-in                     LEAVES for https://elsewhere.test
R20  sign-in   500     (none)                                            not a redirect: node:http refused the Location header: ERR_INVALID_CHAR
     sign-out  500     (none)                                            not a redirect: node:http refused the Location header: ERR_INVALID_CHAR
R21  sign-in   303     //elsewhere%2Etest/sign-in                        LEAVES for https://elsewhere.test
     sign-out  303     //elsewhere%2Etest/sign-in                        LEAVES for https://elsewhere.test
R22  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R23  sign-in   500     (none)                                            not a redirect: node:http refused the Location header: ERR_INVALID_CHAR
     sign-out  500     (none)                                            not a redirect: node:http refused the Location header: ERR_INVALID_CHAR
R24  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
Old session cookie after sign-out, GET /account: 303, Location /sign-in?return_to=%2Faccount
Redirects that leave https://app.example: 12. Responses that were not a redirect: 4.
Server stopped.

VARIANT fixed-origin: same-origin check after sign-in; public route list after sign-out
Listening on 127.0.0.1, port chosen by the system. Public address: https://app.example
GET /account with no session: 303, Location /sign-in?return_to=%2Faccount
Row  Step      Status  Location as sent                                  Parsed against the address posted to
R1   sign-in   303     https://app.example/account                       https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R2   sign-in   303     https://app.example/orders?status=open#latest     https://app.example/orders?status=open#latest: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R3   sign-in   303     https://app.example/account                       https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R4   sign-in   303     https://app.example/account                       https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R5   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R6   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R7   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R8   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R9   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R10  sign-in   303     https://app.example/%2F%2Felsewhere.test/sign-in  https://app.example/%2F%2Felsewhere.test/sign-in: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R11  sign-in   303     https://app.example//elsewhere.test/sign-in       https://app.example//elsewhere.test/sign-in: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R12  sign-in   303     https://app.example/elsewhere.test/sign-in        https://app.example/elsewhere.test/sign-in: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R13  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R14  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R15  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R16  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R17  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R18  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R19  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R20  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R21  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R22  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R23  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R24  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
Old session cookie after sign-out, GET /account: 303, Location /sign-in?return_to=%2Faccount
Redirects that leave https://app.example: 0. Responses that were not a redirect: 0.
Server stopped.

VARIANT fixed-routes: route list after sign-in; public route list after sign-out
Listening on 127.0.0.1, port chosen by the system. Public address: https://app.example
GET /account with no session: 303, Location /sign-in?return_to=%2Faccount
Row  Step      Status  Location as sent                                  Parsed against the address posted to
R1   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R2   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R3   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R4   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R5   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R6   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R7   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R8   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R9   sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R10  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R11  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R12  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R13  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R14  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R15  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R16  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R17  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R18  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R19  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R20  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R21  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R22  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R23  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
R24  sign-in   303     /account                                          https://app.example/account: stays
     sign-out  303     /signed-out                                       https://app.example/signed-out: stays
Old session cookie after sign-out, GET /account: 303, Location /sign-in?return_to=%2Faccount
Redirects that leave https://app.example: 0. Responses that were not a redirect: 0.
Server stopped.
exit code: 0

==== OUTPUT OF node --test redirects.test.mjs (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
✔ R1 plain relative path: sign-in and sign-out stay on https://app.example (11.890417ms)
✔ R2 path with a query and a fragment: sign-in and sign-out stay on https://app.example (1.34525ms)
✔ R3 relative path without a leading slash: sign-in and sign-out stay on https://app.example (1.124ms)
✔ R4 absolute URL to our own site: sign-in and sign-out stay on https://app.example (1.001375ms)
✔ R5 absolute URL to another host: sign-in and sign-out stay on https://app.example (1.196708ms)
✔ R6 protocol-relative address, two slashes: sign-in and sign-out stay on https://app.example (1.059167ms)
✔ R7 three slashes: sign-in and sign-out stay on https://app.example (1.032375ms)
✔ R8 a slash, then a backslash: sign-in and sign-out stay on https://app.example (0.780083ms)
✔ R9 two backslashes: sign-in and sign-out stay on https://app.example (0.731584ms)
✔ R10 encoded slashes: sign-in and sign-out stay on https://app.example (1.124125ms)
✔ R11 encoded dots: sign-in and sign-out stay on https://app.example (0.725375ms)
✔ R12 same scheme, no slashes: sign-in and sign-out stay on https://app.example (0.588208ms)
✔ R13 other scheme, no slashes: sign-in and sign-out stay on https://app.example (0.60025ms)
✔ R14 our host name as a user name: sign-in and sign-out stay on https://app.example (0.592083ms)
✔ R15 user name trick, protocol-relative: sign-in and sign-out stay on https://app.example (1.019917ms)
✔ R16 our host name as a subdomain: sign-in and sign-out stay on https://app.example (0.686875ms)
✔ R17 user name on our own host: sign-in and sign-out stay on https://app.example (0.672375ms)
✔ R18 leading space: sign-in and sign-out stay on https://app.example (0.649458ms)
✔ R19 tab between the slashes: sign-in and sign-out stay on https://app.example (0.62725ms)
✔ R20 newline between the slashes: sign-in and sign-out stay on https://app.example (0.66425ms)
✔ R21 percent-encoding in the host: sign-in and sign-out stay on https://app.example (0.616834ms)
✔ R22 look-alike host (Cyrillic a): sign-in and sign-out stay on https://app.example (0.705541ms)
✔ R23 ideographic full stop in the host: sign-in and sign-out stay on https://app.example (0.567542ms)
✔ R24 javascript: scheme: sign-in and sign-out stay on https://app.example (0.555917ms)
✔ R1 is honoured: /account after sign-in lands on /account (0.379834ms)
✔ after sign-out, the old session cookie no longer opens /account (1.55125ms)
ℹ tests 26
ℹ suites 0
ℹ pass 26
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 137.29775
exit code: 0

==== REGRESSION TEST RESULTS FOR ALL THREE VARIANTS (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
The counts and exit codes are copied from each run's summary lines and exit status.
LAB_VARIANT              tests  pass   fail   exit code
fixed-routes (default)   26     26     0      0
fixed-origin             26     26     0      0
flawed                   26     18     8      1

Test lines from LAB_VARIANT=flawed, in the order the runner printed them:
✔ R1 plain relative path: sign-in and sign-out stay on https://app.example (11.505875ms)
✔ R2 path with a query and a fragment: sign-in and sign-out stay on https://app.example (1.279209ms)
✔ R3 relative path without a leading slash: sign-in and sign-out stay on https://app.example (1.141917ms)
✔ R4 absolute URL to our own site: sign-in and sign-out stay on https://app.example (1.107ms)
✔ R5 absolute URL to another host: sign-in and sign-out stay on https://app.example (1.118167ms)
✖ R6 protocol-relative address, two slashes: sign-in and sign-out stay on https://app.example (1.393833ms)
✖ R7 three slashes: sign-in and sign-out stay on https://app.example (0.883292ms)
✖ R8 a slash, then a backslash: sign-in and sign-out stay on https://app.example (0.611167ms)
✔ R9 two backslashes: sign-in and sign-out stay on https://app.example (0.849ms)
✔ R10 encoded slashes: sign-in and sign-out stay on https://app.example (0.717875ms)
✔ R11 encoded dots: sign-in and sign-out stay on https://app.example (1.213458ms)
✔ R12 same scheme, no slashes: sign-in and sign-out stay on https://app.example (0.661208ms)
✔ R13 other scheme, no slashes: sign-in and sign-out stay on https://app.example (0.689291ms)
✔ R14 our host name as a user name: sign-in and sign-out stay on https://app.example (0.760375ms)
✖ R15 user name trick, protocol-relative: sign-in and sign-out stay on https://app.example (0.469416ms)
✔ R16 our host name as a subdomain: sign-in and sign-out stay on https://app.example (0.822166ms)
✔ R17 user name on our own host: sign-in and sign-out stay on https://app.example (0.748125ms)
✔ R18 leading space: sign-in and sign-out stay on https://app.example (0.7355ms)
✖ R19 tab between the slashes: sign-in and sign-out stay on https://app.example (0.404333ms)
✖ R20 newline between the slashes: sign-in and sign-out stay on https://app.example (0.736833ms)
✖ R21 percent-encoding in the host: sign-in and sign-out stay on https://app.example (0.529583ms)
✔ R22 look-alike host (Cyrillic a): sign-in and sign-out stay on https://app.example (0.909ms)
✖ R23 ideographic full stop in the host: sign-in and sign-out stay on https://app.example (0.58725ms)
✔ R24 javascript: scheme: sign-in and sign-out stay on https://app.example (0.811625ms)
✔ R1 is honoured: /account after sign-in lands on /account (0.430833ms)
✔ after sign-out, the old session cookie no longer opens /account (0.963083ms)

Failure messages from LAB_VARIANT=flawed, in order. Each was followed by a diff, a stack trace naming a local file path and the error's properties, cut here.
  AssertionError [ERR_ASSERTION]: flawed sent Location //elsewhere.test/sign-in
  AssertionError [ERR_ASSERTION]: flawed sent Location ///elsewhere.test/sign-in
  AssertionError [ERR_ASSERTION]: flawed sent Location /\elsewhere.test/sign-in
  AssertionError [ERR_ASSERTION]: flawed sent Location //app.example@elsewhere.test/sign-in
  AssertionError [ERR_ASSERTION]: flawed sent Location /(TAB)/elsewhere.test/sign-in
  AssertionError [ERR_ASSERTION]: flawed answered 500 instead of a redirect
  AssertionError [ERR_ASSERTION]: flawed sent Location //elsewhere%2Etest/sign-in
  AssertionError [ERR_ASSERTION]: flawed answered 500 instead of a redirect

==== READING THE OUTPUT ====
Part A, per row:
  input: the value a handler receives. (SP), (TAB) and (LF) name a space, a tab and a line feed.
  outside ASCII: each character beyond ASCII, with its position counted from 1.
  new URL(input, base) and origin: what the Node.js URL class reported, with https://app.example/sign-in as the base.
  username: shown when the parser found a user name.
  decoded once more: shown when decodeURIComponent() changes the value, with where the result would land.
  The five checks: "accepts" and "sends" give the Location the check would send and where new URL() lands it from the base. "stays" means on https://app.example; "LEAVES" means another origin. "refuses" means the check sent its fallback, /account.
Part B, per row:
  Location as sent: the header exactly as the client received it, (none) if there was none.
  Parsed against the address posted to: new URL(Location, base), where the base is https://app.example/sign-in or https://app.example/sign-out.
  not a redirect: the status was not 303, followed by the body the server sent.

==== BROWSER ASSERTIONS: CONFIRM IT IN YOUR OWN BROWSER ====
The lab shows what a server sends. To see what your browser does with it, run these steps against a copy of your own application, such as a staging site, with a test account. Put your site's address where the table has https://app.example, use your real parameter name in place of return_to, and keep elsewhere.test, or another name under a top level name that RFC 2606 reserves, such as .test or .invalid, as the other host.
1. Open the browser's developer tools on the Network panel, and turn on the option that keeps the log when the page changes.
2. Sign out. Open your sign-in page with a return address from the table in its link, percent-encoded, for example /sign-in?return_to=%2F%2Felsewhere.test%2Fsign-in for R6.
3. Sign in. In the Network panel, select the request the sign-in form sent, and read the response's status and its Location header.
4. Assert that the status is a redirect and that the Location, read against the address the form posted to, names your own origin. Then look at the next request in the log and at the address bar. If either shows elsewhere.test, the redirect left your site.
5. Sign out with the same return address, by whatever route your sign-out takes it, and make the same assertions on the sign-out response.
6. After sign-out, open a page that needs sign-in, or use the back button and reload. You should land on the sign-in page, not see the account.
7. Repeat for each row of the table, and add the return addresses your application really uses, so you also see when a check refuses a legitimate one.

==== WHAT WAS NOT TESTED ====
The lab ran on Node.js on macOS only, and no browser was run. What a browser does with each Location comes from the Fetch Standard and RFC 9110, not from this lab. Other servers and frameworks may send, encode or refuse the same header values differently: node:http threw ERR_INVALID_CHAR for R20 and R23, so the flawed variant answered 500 for those rows. Client-side redirects through window.location, server-side forwards, and redirects inside OAuth or OpenID Connect flows are not part of the lab.

==== USING THE TEST ON YOUR OWN CODE ====
1. List every place your code redirects: Location headers written directly, your framework's redirect helper, sign-in, sign-out, sign-up and email confirmation flows, and client-side code that assigns window.location or location.href.
2. For each one, find where the destination comes from. If any part of it comes from the request, a cookie, a hidden form field or a stored record, it belongs in the test.
3. Copy return-address.mjs and redirects.test.mjs, replace SITE_ORIGIN and the route lists with your own, and point the test at a running copy of your application, or call your redirect function directly in place of lab-server.mjs.
4. Keep the assertion: the status is a redirect, and the Location, parsed against the address the browser posted to, has your origin.
5. Keep a row for every input class, and add your real return addresses, so the test also shows when the check is stricter than it needs to be.
6. Keep the test in your suite, so a later change that loosens the check fails a build instead of reaching production.

What an open redirect vulnerability is

An open redirect is a page or endpoint on your site that sends the browser to an address taken from the request, without checking where that address leads.

MITRE catalogues the weakness as CWE-601, URL Redirection to Untrusted Site: the web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a redirect. Its alternate terms include Open Redirect, Unvalidated Redirect, Cross-site Redirect and Cross-domain Redirect.

OWASP's Unvalidated Redirects and Forwards Cheat Sheet describes the same flaw as a web application that accepts untrusted input that could cause it to redirect the request to a URL contained within that input.

What it lends an attacker is your name. The cheat sheet says that by modifying the URL to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials, and that because the server name in the modified link is identical to the original site, phishing attempts may have a more trustworthy appearance.

CWE-601 adds that the user may be redirected to an untrusted page that contains malware, and that in some cases an open redirect can also enable the immediate download of a file without the user's permission.

The cheat sheet and the WSTG's client-side redirect test, WSTG-CLNT-04, also both say such a URL can be crafted to pass the application's access control check and forward the attacker to privileged functions they would normally not be able to access.

An open redirect is also a step in other attacks. RFC 9700, the OAuth 2.0 Security Best Current Practice, says clients and authorisation servers MUST NOT expose URLs that forward the user's browser to arbitrary URIs obtained from a query parameter, and that open redirectors can enable exfiltration of authorisation codes and access tokens.

The SSRF guide in this library shows the server-side version: an open redirect on a host that a server is allowed to fetch from can carry the server's request past its allowlist.

In the standards, OWASP's Top 10:2025 lists CWE-601 among the CWEs mapped to A01:2025 Broken Access Control. ASVS 5.0 requirement 3.7.2, at Level 2, asks that the application only automatically redirects the user to a different hostname or domain, not controlled by the application, where the destination appears on an allowlist.

CWE-601 also notes that whether the issue poses a vulnerability depends on the intended behaviour of the application, and gives the example of a search engine that might intentionally provide redirects to arbitrary URLs.

This guide covers the redirect a browser follows: a return address such as return_to or next, taken from the request, and how to prove yours only sends people to your own pages. Redirect URIs in a sign-in through another provider are matched by that provider, as the OAuth and OIDC security guide explains.

When your server follows a URL itself, rather than the browser, the problem is server-side request forgery, covered in the SSRF guide. A site that builds its own address from the Host header has a separate problem, covered in the host header injection guide, and what a token or personal detail left in a URL can expose is covered in the sensitive data exposure guide. The Next.js guide covers that framework's own settings.

Return URL security: what a return address is for

A return address exists for a good reason.

Someone opens a page that needs sign-in, such as /account, the application sends them to the sign-in page, and it remembers where they were going so it can take them there afterwards. The address travels in the link or in the form, in a parameter with a name such as return_to, next, returnUrl, redirect or continue.

In the lab on this page, a request for /account with no session came back as a 303 with Location /sign-in?return_to=%2Faccount.

Once the password is accepted, the server answers with a redirect: a 3xx status and a Location header. RFC 9110 says that for 3xx responses the Location value refers to the preferred target resource for automatically redirecting the request, and that when the value is a relative reference, the final value is computed by resolving it against the target URI.

It describes 303 See Other as primarily used to allow the output of a POST action to redirect the user agent to a different resource, which is the shape of a sign-in form.

The trouble is that the return address arrives with the request, so anyone can write a link that carries their own. The second of the cheat sheet's two redirect examples is a sign-in action: the LogOn action of an ASP.NET MVC 2 application, which returns a redirect to the returnUrl after a successful login, with no validation performed against that parameter.

Moving the value into a cookie or a hidden form field does not change who controls it.

CWE-601 notes that many open redirect problems occur because the programmer assumed that certain inputs could not be modified, such as cookies and hidden form fields.

Places to look for a destination that comes from the request:

  • Sign-in and sign-up, once the password or the email confirmation succeeds.
  • Sign-out, where a link can name the page to show afterwards.
  • Password reset and email change confirmations that send people on when they finish.
  • Language, currency or region switchers that return to the page you were on.
  • Outbound link and click-tracking endpoints, such as /out?url= followed by an address.
  • Client-side code that reads a value from the query string or the fragment and assigns it to window.location. WSTG-CLNT-04 names window.location as one way client-side redirects are implemented in JavaScript.

How a browser reads the Location header

Before judging any check, it helps to know what decides where the browser goes.

It is not your check: it is the browser's URL parser. The Fetch Standard defines a response's location URL as the Location value parsed with the response's URL, and says that algorithm is used for redirect handling in Fetch itself and in HTML's navigate algorithm.

The parser it uses is the WHATWG URL Standard's, and Node.js documents its WHATWG URL API, which includes the URL class, as implementing the same WHATWG URL Standard that web browsers use.

That makes new URL(value, base) in Node.js, with the address the form posted to as the base, a fair stand-in for how a browser that follows these standards reads the same Location value.

The parser accepts a great deal that a strict reading would reject. RFC 9110 says a Location field consists of a single URI reference, and notes that some recipients attempt to recover from Location values that are not valid URI references, which it neither mandates nor defines but allows for the sake of robustness.

The URL Standard records odd input as a validation error and, unless a step says to return failure, carries on: it says a validation error does not mean that the parser terminates. The table on this page shows what it made of each one.

That is also why the lab's scripted client is careful about what it shows. It records the status and the Location header each server variant sent, and parses each Location with new URL() against the address the browser would have posted to.

It does not run a browser. Where a browser goes next is what the standards above describe, and the steps at the end of the lab show how to confirm it in your own browser's developer tools.

Why "starts with a slash" and "contains our domain" both fail

Two tempting checks both read the text.

One accepts any value that starts with a slash, on the reasoning that it must be a path on this site. The other accepts any value that mentions the site's own host name. The parser does not read the text the way either check does.

Of the lab's 24 inputs, the slash check let 8 land on another host and the host name check let 3 through, 10 different inputs between them.

Two slashes, three slashes and a backslash

A value that starts with two slashes is not a path. 1 min read

Tabs, newlines and leading spaces

Before any of that, the parser cleans the input. 1 min read

User names and subdomains

The host name check fails the other way round. 1 min read

A scheme with no slashes

A scheme does not need slashes after it. 1 min read

Percent-encoding and international host names

The host is decoded before anything is compared. 1 min read

Encoded slashes and dots, and decoding twice

Percent-encoded slashes in a path stay encoded. /%2F%2Felsewhere.test/sign-in (R10) parsed to a path on https://app.example, because %2F is not a separator to the parser. 1 min read

javascript: and other schemes

The URL Standard gives a tuple origin to ftp, http, https, ws and wss URLs, and a new opaque origin to schemes it does not list; javascript:alert(1) (R24) reported the origin null. 1 min read

Open redirect prevention: check the parsed result, not the text

Every gap above has the same cause: the check read one thing and the browser parsed another.

The fix is to parse the value once, with a parser that follows the same standard as the browser, check what the parser produced, and redirect to that result. The cheat sheet's section on validating URLs says, among other things, to use a maintained URL parser compatible with the redirect API and browser URL interpretation, compare the parsed scheme, canonical host and effective port against an explicit allowlist, reject userinfo and ambiguous input, and redirect using the validated URL rather than transforming it afterward.

The Node.js URL documentation gives the same advice for this case: where it is not known in advance whether the input is an absolute URL and a base is provided, validate that the origin of the URL object is what is expected.

The lab's checkSameOrigin() does that in four steps:

  • Refuse a value that contains a C0 control character, a space, DEL or a backslash. The parser strips some of these from the ends, removes tabs and newlines anywhere and, in an http or https URL, reads a backslash as a slash, and the cheat sheet says to reject ambiguous input.
  • Parse it with new URL(value, siteOrigin + '/'), and refuse anything that throws.
  • Accept it only if the parsed origin equals your site's origin exactly, and it carries no user name or password.
  • Redirect to the parsed URL's href: never to the original text, and never to a piece of it.

Your origin is configuration, not input

The check is only as good as the origin it compares with. Configure your site's public origin as a setting. If it is read from the request's Host header, whoever sends the request decides what counts as your site, which the host header injection guide covers.

When the check refuses a value, send people to a sensible default rather than an error page. In the lab a refused value goes to /account after sign-in and to /signed-out after sign-out.

Framework redirect helpers do not check for you

A redirect helper sends the browser wherever it is told. The Next.js documentation says its redirect() function takes a relative or absolute path, and also accepts absolute URLs and can be used to redirect to external links, so passing a request value straight to it repeats the flaw.

The cheat sheet's advice for local return URLs is a framework helper that rejects non-local destinations, and it names ASP.NET Core's LocalRedirect and IsLocalUrl. Where your framework has no such helper, a function like checkSameOrigin() is that helper.

Why a redirect allowlist of routes beats validating a URL

A same-origin check still accepts any page on your site, and still depends on parsing a value someone else wrote.

The stronger approach takes the parsing out: accept a route name, or a path on an explicit list, and build the redirect yourself from that list. The cheat sheet says that where possible, the user should provide a short name, ID or token which is mapped server-side to a full target URL, and that this provides the highest degree of protection against the attack tampering with the URL.

Its section on validating URLs ends by saying a server-side mapping from an approved destination ID remains preferable to accepting arbitrary URLs. CWE-601 calls the idea enforcement by conversion: when the set of acceptable objects, such as file names or URLs, is limited or known, create a mapping from a set of fixed input values, such as numeric IDs, to the actual file names or URLs, and reject all other inputs.

The lab's checkRouteList() accepts account, orders or billing, or the matching path, and sends the path from its own table. In the live lab, every sign-in to the fixed-routes variant answered with Location /account and every sign-out with /signed-out, whichever of the 24 inputs it was given, because nothing from the request reached the header. There is no second reading of the value to disagree with the first.

There is a cost, and the table shows it. The route list refused /orders?status=open#latest (R2), because that exact text is not on the list, and sent the default instead; the same-origin check kept it.

Where people need to come back to one particular record, keep the address on the server, for example in the session when you send them to sign in, and put only an identifier in the link.

The cheat sheet's caution applies to identifiers: be careful that the mapping does not introduce an enumeration vulnerability where a user could cycle through IDs to find all possible redirect targets.

When you must send people to another site

Some flows do need to leave your site, to a payment provider or a partner. ASVS 5.0 requirement 3.7.2 (Level 2) allows an automatic redirect to a hostname or domain the application does not control only where the destination appears on an allowlist, and requirement 3.7.3 (Level 3) asks the application to show a notification when the user is being redirected to a URL outside its control, with an option to cancel the navigation.

Among the ways the cheat sheet lists are allow-listing explicitly approved external destinations using the parsed URL components, and sending all redirects first through a page that tells users they are leaving your site, with the destination clearly displayed and a link to confirm. CWE-601 warns to avoid cross-site scripting when generating such a disclaimer page.

What changes after sign-out

Sign-out has a return address too, and two things change.

First, nothing behind sign-in is left to return to: send a signed-out visitor to /account, and a site like the lab's sends them straight back to the sign-in page. So the list should shrink to public pages. In the lab, both fixed variants accept only home, signed-out or sign-in after sign-out, and send everything else to /signed-out.

The flawed variant used the same slash check for both flows, and its sign-out left for elsewhere.test on the same six inputs as its sign-in.

Second, the session has to end on the server, not only in the browser, before the redirect is sent. ASVS 5.0 requirement 7.4.1 (Level 1) asks that when session termination is triggered, such as by logout, the application disallows any further use of the session.

Each lab variant deletes the session on the server, and a request for /account with the old cookie after sign-out was sent back to the sign-in page. The session management guide in this library covers the rest of sign-out.

A sign-out link on your own domain that lands on someone else's page has the shape the cheat sheet describes: the server name in the link is identical to the original site, and the redirect takes the visitor elsewhere.

If sign-out goes through an identity provider, the provider keeps its own list. OpenID Connect RP-Initiated Logout 1.0 says the post_logout_redirect_uri MUST have been previously registered with the provider, and that the provider MUST NOT perform post-logout redirection if the value supplied does not exactly match one of the registered values.

That list covers the trip back to your application. Any redirect your application makes after it is still yours to check.

Testing for open redirects in code and in a browser

WSTG-CLNT-04 sets two objectives: identify injection points that handle URLs or paths, and assess the locations that the system could redirect to.

In code, that means finding every redirect and tracing its destination back. Search for Location headers written directly, your framework's redirect helper, and client-side assignments to window.location or location.href, then follow each destination to where it came from: a query parameter, a form field, a cookie or a stored record.

CWE-601 is plain about automated tools. It says automated black box tools that supply URLs to every input may be able to spot Location header modifications, but test case coverage is a factor and custom redirects may not be detected, and that automated static analysis tools may not be able to determine whether input influences the beginning of a URL, which is important for reducing false positives.

That is a reason to list your own redirect flows rather than rely on a scan to find them.

To test a running copy, use the table's inputs with the other host under a top level name that RFC 2606 reserves, such as elsewhere.test under .test, on an application you own or are authorised in writing to test, and with test accounts.

Read the status and the Location header of each sign-in and sign-out response, as the lab's client does, and confirm what the browser did with the steps at the end of the lab.

Then keep the cases in a regression test like redirects.test.mjs, which asserts that every sign-in and sign-out answers with a redirect whose Location, parsed against the address posted to, stays on your origin.

Walking through the redirect lab

The lab is an illustration written for this page, not a client's code.

It needs Node.js and nothing else, and every output was recorded on Node.js v26.0.0 on macOS. parser-table.mjs parses 24 return addresses with new URL() against https://app.example/sign-in and runs each through five checks: the two naive ones, the path-only near-fix and the two fixed checks. client.mjs starts a sign-in and sign-out server on 127.0.0.1 in three variants, one at a time, signs in and out once per input, and prints the status and Location each variant sent.

The server is configured with https://app.example as its public address, the way an application behind a proxy is, so the client never connects to anything but the lab server.

What the table showed

The slash check let 8 of the 24 inputs land on another origin: two and three slashes, a slash then a backslash, the user name trick written protocol-relative, the tab and the newline, the encoded dot in the host and the ideographic full stop.

The host name check let 3 through, all of them with app.example in the text and another host in the URL. The path-only near-fix let 1 through, R11. Neither fixed check let any through.

The same-origin check accepted seven values, each on https://app.example, including the query and fragment in R2, and refused the rest. The route list accepted two, R1 and R3, and sent every other input to /account.

What the servers sent

The flawed variant sent 12 redirects that, parsed against the address posted to, leave https://app.example: six inputs, each after sign-in and after sign-out. It answered 500 four times, for R20 and R23, when node:http threw ERR_INVALID_CHAR on the newline and on the ideographic full stop.

The fixed-origin and fixed-routes variants sent no redirect that leaves and no error. In every variant, the old session cookie no longer opened /account after sign-out.

The regression test

redirects.test.mjs runs 26 tests against the variant LAB_VARIANT names: one per input, asserting that sign-in and sign-out both answer 303 with a Location that stays on https://app.example, one asserting that a legitimate /account is honoured, and one asserting that the old cookie stops working after sign-out. Both fixed variants passed all 26.

The flawed variant failed 8 and exited with code 1, which the Node.js test runner documentation says it sets when any test fails. The lab was not run on Windows, Linux or in a browser, and other servers may treat the same header values differently from node:http.

Where an outside test fits

The lab checks the redirects you already know about.

A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. Read-only code access to named areas can be added to the scope, and a finding that rests on the code alone says so.

Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

It is a page or endpoint that sends the browser to an address taken from the request without checking where it leads. MITRE catalogues it as CWE-601, URL Redirection to Untrusted Site, and lists Open Redirect and Unvalidated Redirect among its alternate terms. OWASP's cheat sheet says that because the server name in such a link is identical to the original site, phishing attempts may have a more trustworthy appearance.

No. In the lab, values starting with two or three slashes, a slash then a backslash, or a slash, a tab and a slash all started with / and parsed to another host, because the URL Standard's parser removes the tab, skips the extra slashes and backslashes, and passes what follows to the authority state, which reads the host. Check the origin of the parsed result, or better, accept only a route on an explicit list.

Refuse control characters, spaces and backslashes, parse the value with new URL(value, siteOrigin + '/'), accept it only if the result's origin equals your configured origin and it has no user name or password, and redirect to the parsed href. The Node.js URL documentation advises validating the origin of the URL object when a base is provided and it is not known in advance whether the input is absolute. A route allowlist is stronger again.

Not by itself. The Next.js documentation says redirect() accepts relative and absolute paths, and also accepts absolute URLs and can be used to redirect to external links. Check the destination first, or map a route name to a path you choose, before calling it.

A fixed list of destinations your code chooses from, keyed by a short name or ID, so nothing from the request reaches the Location header. OWASP's cheat sheet says that, where possible, having the user provide a short name, ID or token mapped server-side to a full target URL provides the highest degree of protection against the attack tampering with the URL. For destinations on other sites, ASVS 5.0 requirement 3.7.2 asks for an allowlist too.

For the other host, use a name under a top level name that RFC 2606 reserves, such as elsewhere.test under .test. Test only an application you own or are authorised in writing to test, and use test accounts. Read the status and Location of each sign-in and sign-out response, confirm in your browser's developer tools, and keep the cases in a regression test.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.