/**
 * Same-origin validation for user-supplied redirect targets.
 *
 * Every `?redirect=` sink in the auth flow used to pass the query value
 * straight to `c.redirect()`. `/login?redirect=https://evil.example` sent the
 * browser to the attacker's site carrying the platform's own domain in the
 * link the victim clicked — the classic phishing primitive, and worse on a
 * sign-in page than anywhere else, because the victim has just been asked to
 * type a password and the attacker controls where they land immediately
 * after. It also lets an attacker bounce a freshly-authenticated user to a
 * page that harvests whatever the app puts in the URL.
 *
 * The policy here is deliberately narrow: accept a relative path on this
 * origin, reject everything else. Absolute URLs are refused even when they
 * point at our own host — allowing them means parsing and comparing origins,
 * and origin comparison is exactly where these bugs come from.
 *
 * Rejected, with the reason each one matters:
 *
 *   https://evil.example    absolute URL, different origin
 *   //evil.example          protocol-relative; browsers treat it as absolute
 *   /\evil.example          browsers fold a backslash to a slash, so this
 *                           behaves like the protocol-relative case above
 *   javascript:alert(1)     scheme URL, no leading slash
 *   /foo\r\nSet-Cookie: x   control characters, i.e. header injection
 *   (empty / missing)       nothing to honour
 *
 * Accepted: `/dashboard`, `/owner/repo/pulls?state=open#tab`, `/` — a single
 * leading slash, no backslash anywhere, no control characters.
 *
 * Note on encoding: Hono has already percent-decoded the query value by the
 * time it reaches here, so `%2f%2fevil.example` arrives as `//evil.example`
 * and `%0d%0a` arrives as real control characters. Both are caught above.
 * Validate the decoded value — never the raw one.
 */

/**
 * A single leading slash, not followed by another slash, then any run of
 * characters that are neither backslashes nor C0/C1 control characters.
 */
const SAFE_PATH = /^\/(?!\/)[^\\\x00-\x1f\x7f-\x9f]*$/;

/** True if `value` is a relative path safe to redirect to on this origin. */
export function isSafeRedirect(value: unknown): value is string {
  if (typeof value !== "string") return false;
  if (value.length === 0) return false;
  return SAFE_PATH.test(value);
}

/**
 * Return `value` when it is a safe same-origin path, otherwise `fallback`.
 *
 * Always use this — never the raw query value — when building a `Location`
 * header from anything the caller supplied.
 */
export function safeRedirect(value: unknown, fallback: string = "/"): string {
  return isSafeRedirect(value) ? value : fallback;
}
