Skip to the code

Sign in, then back to next, safely

When a signed-out visitor opens a page that needs an account, like /account/orders, Leaf and Kettle sends them to /sign-in?next=/account/orders, so they can carry on there once they've signed in. Build the sign-in form, app/sign-in/sign-in-form.tsx: a Client Component whose default export is SignInForm, and which also exports safeNextPath(next).

The form has inputs labelled Email and Password and a Sign in submit button. On submit, call signIn(email, password) from @/lib/auth. When it returns false, show Wrong email or password. in an element with role="alert". When it returns true, go to safeNextPath of the URL's next with router.replace, so Back doesn't lead to the form again.

Anyone can send a link with any next, so following it blindly makes the shop an open redirect: /sign-in?next=https://evil.example would take a visitor who just signed in to another site, and a javascript: URL would run code on the shop's page. safeNextPath(next) returns a path on this site, and /account for anything else:

next must start with /, and once a browser resolves it against the shop's address, it must still be on the shop. //evil.example and /\evil.example are other sites to a browser, and so is ?next=/%09/evil.example, whose next is /, a tab, and /evil.example, because browsers drop tabs and newlines from URLs. A next that can't be parsed at all gets /account too.

It must not be /sign-in or a page under it, which would only show the form again.

For a safe next, return its path, search, and hash: /teas/green?tab=reviews#write.

safeNextPath("/account/orders?page=2")  → "/account/orders?page=2"
safeNextPath("https://evil.example")    → "/account"
safeNextPath("//evil.example")          → "/account"
safeNextPath(null)                      → "/account"

The app's other files

lib/auth.ts, read-only. Import it as @/lib/auth.

/** Every email someone tried to sign in with, in order. */
export const attempts: string[] = [];
 
/** Checks an email and password against the shop's accounts: true when they match. */
export async function signIn(email: string, password: string): Promise<boolean> {
  attempts.push(email);
  return email === "ana@example.com" && password === "oolong-42";
}

What the tests check

  1. safeNextPath keeps a path on this site, with its search and hash
    for (const path of ["/account/orders?page=2", "/teas/green?tab=reviews#write", "/"]) expect(safeNextPath(path)).toBe(path);
    
  2. safeNextPath sends anything else to /account
    const unsafe = [null, "", "account/orders", "https://evil.example/account", "//evil.example", "/\\evil.example", "/\t/evil.example", "/\n/evil.example", "javascript:alert(1)", "//[", "/sign-in", "/sign-in?next=/account", "/sign-in/help"];
    for (const next of unsafe) expect(safeNextPath(next)).toBe("/account");
    
  3. signs in and replaces the sign-in page with next
    const signInWith = async (password) => {
      await user.type(screen.getByLabelText("Email"), "ana@example.com");
      await user.type(screen.getByLabelText("Password"), password);
      await user.click(screen.getByRole("button", { name: "Sign in" }));
    };
    renderClient(<SignInForm />, { url: "/sign-in?next=%2Faccount%2Forders%3Fpage%3D2" });
    await signInWith("oolong-42");
    await waitFor(() => expect(router.url).toBe("/account/orders?page=2"));
    expect(router.history).toEqual(["/account/orders?page=2"]);
    expect(router.calls.map((call) => call.method)).toEqual(["replace"]);
    expect(attempts).toEqual(["ana@example.com"]);
    
  4. goes to /account without a next
    const signInWith = async (password) => {
      await user.type(screen.getByLabelText("Email"), "ana@example.com");
      await user.type(screen.getByLabelText("Password"), password);
      await user.click(screen.getByRole("button", { name: "Sign in" }));
    };
    renderClient(<SignInForm />, { url: "/sign-in" });
    await signInWith("oolong-42");
    await waitFor(() => expect(router.url).toBe("/account"));
    expect(router.history).toEqual(["/account"]);
    
  5. never follows next off the site
    const signInWith = async (password) => {
      await user.type(screen.getByLabelText("Email"), "ana@example.com");
      await user.type(screen.getByLabelText("Password"), password);
      await user.click(screen.getByRole("button", { name: "Sign in" }));
    };
    renderClient(<SignInForm />, { url: "/sign-in?next=https://evil.example/steal" });
    await signInWith("oolong-42");
    await waitFor(() => expect(router.url).toBe("/account"));
    cleanup();
    renderClient(<SignInForm />, { url: "/sign-in?next=/%09/evil.example" });
    await signInWith("oolong-42");
    await waitFor(() => expect(router.url).toBe("/account"));
    expect(router.calls.map((call) => [call.method, call.href])).toEqual([
      ["replace", "/account"],
      ["replace", "/account"],
    ]);
    
  6. shows an error and stays put when the password is wrong
    const signInWith = async (password) => {
      await user.type(screen.getByLabelText("Email"), "ana@example.com");
      await user.type(screen.getByLabelText("Password"), password);
      await user.click(screen.getByRole("button", { name: "Sign in" }));
    };
    renderClient(<SignInForm />, { url: "/sign-in?next=/account/orders" });
    await signInWith("green-42");
    expect(await screen.findByRole("alert")).toHaveTextContent("Wrong email or password.");
    expect(router.calls).toEqual([]);
    expect(router.url).toBe("/sign-in?next=/account/orders");
    

Learn more

app/sign-in/sign-in-form.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).