/**
 * Regression guard: open redirect on the sign-in flow.
 *
 * Every `?redirect=` sink in auth.tsx passed the query value straight to
 * `c.redirect()`. `/login?redirect=https://evil.example` sent the browser to
 * the attacker's site from a link carrying the platform's own domain — the
 * classic phishing primitive, and at its worst on a sign-in page, because
 * the victim has just been asked for a password and the attacker chooses
 * where they land immediately afterwards.
 *
 * Hono percent-decodes the query value before a handler sees it, so
 * `%2f%2fevil.example` arrives as `//evil.example` and `%0d%0a` arrives as
 * real control characters. The decoded value is what these cases cover.
 */

import { describe, it, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { safeRedirect, isSafeRedirect } from "../lib/safe-redirect";

describe("isSafeRedirect rejects off-origin targets", () => {
  const attacks: Array<[string, string]> = [
    ["https://evil.example", "absolute URL"],
    ["http://evil.example/x", "absolute URL, plain http"],
    ["//evil.example", "protocol-relative — browsers treat it as absolute"],
    ["//evil.example/path?a=b", "protocol-relative with a path"],
    ["/\\evil.example", "browsers fold the backslash to a slash"],
    ["\\\\evil.example", "UNC-style, folds to protocol-relative"],
    ["javascript:alert(1)", "scheme URL"],
    ["data:text/html,<script>", "data URL"],
    ["  /dashboard", "leading whitespace, no leading slash"],
    ["dashboard", "bare relative path, not rooted"],
    ["", "empty"],
  ];

  for (const [value, why] of attacks) {
    it(`rejects ${JSON.stringify(value)} (${why})`, () => {
      expect(isSafeRedirect(value)).toBe(false);
      expect(safeRedirect(value, "/dashboard")).toBe("/dashboard");
    });
  }

  it("rejects control characters (header injection)", () => {
    expect(isSafeRedirect("/foo\r\nSet-Cookie: a=b")).toBe(false);
    expect(isSafeRedirect("/foo\nLocation: https://evil.example")).toBe(false);
    expect(isSafeRedirect("/foo\tbar")).toBe(false);
    expect(isSafeRedirect("/foo\x00bar")).toBe(false);
  });

  it("rejects non-strings", () => {
    expect(isSafeRedirect(undefined)).toBe(false);
    expect(isSafeRedirect(null)).toBe(false);
    expect(isSafeRedirect(42)).toBe(false);
    expect(isSafeRedirect(["/a"])).toBe(false);
  });
});

describe("isSafeRedirect accepts ordinary same-origin paths", () => {
  const ok = [
    "/",
    "/dashboard",
    "/onboarding?welcome=1",
    "/ccantynz/Gluecron.com/pulls?state=open",
    "/settings/tokens#new",
    "/a/b/c/d/e",
    "/repo/with-dash_and.dot",
    "/search?q=hello+world&page=2",
  ];

  for (const value of ok) {
    it(`accepts ${JSON.stringify(value)}`, () => {
      expect(isSafeRedirect(value)).toBe(true);
      expect(safeRedirect(value, "/fallback")).toBe(value);
    });
  }

  it("defaults the fallback to the site root", () => {
    expect(safeRedirect("https://evil.example")).toBe("/");
  });
});

// --- the sinks must actually use it ----------------------------------------
//
// The bug was an absent check, so testing the helper alone would not have
// caught it. Strip ONLY line comments: a block-comment regex eats route
// paths, which contain a slash followed by a star.

function sourceWithoutLineComments(...rel: string[]): string {
  const text = readFileSync(join(import.meta.dir, "..", ...rel), "utf8");
  const stripped = text
    .split("\n")
    .filter((l) => !l.trim().startsWith("//"))
    .join("\n");
  expect(stripped.length).toBeGreaterThan(0);
  return stripped;
}

describe("redirect sinks are validated", () => {
  it("auth.tsx never reads the redirect query without validating it", () => {
    const src = sourceWithoutLineComments("routes", "auth.tsx");
    // Every read of the parameter must be wrapped. If a new sink is added
    // with a bare `c.req.query("redirect")`, this fails.
    const bare = src.match(/(?<!safeRedirect\(\s*)c\.req\.query\("redirect"\)/g);
    expect(bare).toBeNull();
    // ...and the helper is genuinely in use, so the check above cannot pass
    // vacuously by the sinks having been deleted.
    expect(src).toContain("safeRedirect(c.req.query(\"redirect\")");
    const uses = src.split("safeRedirect(").length - 1;
    expect(uses).toBeGreaterThanOrEqual(5);
  });

  it("personal-chat.tsx validates its form-supplied redirect", () => {
    const src = sourceWithoutLineComments("routes", "personal-chat.tsx");
    expect(src).toContain("safeRedirect(body.redirect");
    expect(src).not.toContain('String(body.redirect || "/chat")');
  });
});
