import { describe, expect, it } from "vitest"; import { internalUrl, safeReturnTo } from "#lib/auth/returnTo.ts"; describe("safeReturnTo", () => { it("keeps same-origin paths with query and hash", () => { expect(safeReturnTo("/alice.tngl.sh/core?tab=pulls#c1")).toBe( "/alice.tngl.sh/core?tab=pulls#c1" ); }); it("rejects network-path references", () => { expect(safeReturnTo("//evil.example")).toBe("/"); expect(safeReturnTo("/\\evil.example")).toBe("/"); expect(safeReturnTo("\\\\evil.example")).toBe("/"); }); it("rejects absolute and non-http targets", () => { expect(safeReturnTo("https://evil.example/repo")).toBe("/"); expect(safeReturnTo("javascript:alert(1)")).toBe("/"); }); it("normalizes scheme-relative input that stays on the origin", () => { // the URL parser reads this as a same-origin path, not a host expect(safeReturnTo("https:/evil.example")).toBe("/evil.example"); }); it("falls back for empty or non-string input", () => { expect(safeReturnTo("")).toBe("/"); expect(safeReturnTo(" ")).toBe("/"); expect(safeReturnTo(undefined)).toBe("/"); expect(safeReturnTo(42)).toBe("/"); }); }); describe("internalUrl", () => { it("reports a rejected target instead of inventing one", () => { expect(internalUrl("/repo/migrate?knot=at")?.href).toBe( "https://return-to.invalid/repo/migrate?knot=at" ); expect(internalUrl("//evil.example")).toBeNull(); expect(internalUrl("https://evil.example/")).toBeNull(); expect(internalUrl("")).toBeNull(); expect(internalUrl(undefined)).toBeNull(); }); });