kit icon indicating copy to clipboard operation
kit copied to clipboard

HTTP Basic Auth x hard linking with username/password in URL

Open frederichoule opened this issue 1 year ago • 1 comments

Describe the bug

When you add HTTP Basic Auth to a sveltekit app, and then hard link to the app using the username/password in the URL, we get an error about replaceState on History because there is an URL mismatch.

Reproduction

Reproduction repo: https://github.com/frederichoule/sveltekit-http-auth-bug

How to reproduce manually:

  1. Create a new sveltekit app from scratch
  2. Create src/hooks.server.ts and insert this code:
import type { Handle } from "@sveltejs/kit";
import { building } from '$app/environment'

export const handle = (async ({ event, resolve }) => {

    if (building) {
        const response = await resolve(event)
        return response;
    }

    const auth = event.request.headers.get("Authorization");

    if (auth !== `Basic ${btoa('username:password')}`) {
        return new Response("Not authorized", {
            status: 401,
            headers: {
                "WWW-Authenticate":
                    'Basic realm="Bug", charset="UTF-8"',
            },
        });
    }

    return resolve(event);
}) satisfies Handle;
  1. Start the app npm run dev
  2. Type the direct link with username/password in your browser address bar: http://username:password@localhost:5173
  3. Check console

Logs

Uncaught (in promise) DOMException: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://localhost:5173/' cannot be created in a document with origin 'http://localhost:5173' and URL 'http://username:password@localhost:5173/'.
    at create_client (http://localhost:5173/node_modules/@sveltejs/kit/src/runtime/client/client.js?v=8b7c5880:126:11)
    at Module.start (http://localhost:5173/node_modules/@sveltejs/kit/src/runtime/client/start.js:17:17)
    at http://username:password@localhost:5173/:1009:11

System Info

System:
    OS: macOS 13.5
    CPU: (8) arm64 Apple M2
    Memory: 79.00 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.16.0 - ~/Library/Caches/fnm_multishells/22346_1691606203721/bin/node
    npm: 9.5.1 - ~/Library/Caches/fnm_multishells/22346_1691606203721/bin/npm
  Browsers:
    Chrome: 115.0.5790.170
    Safari: 16.6
  npmPackages:
    @sveltejs/adapter-auto: ^2.0.0 => 2.1.0
    @sveltejs/adapter-cloudflare: ^2.3.2 => 2.3.2
    @sveltejs/kit: ^1.20.4 => 1.22.4
    svelte: ^4.0.5 => 4.1.2
    vite: ^4.4.2 => 4.4.9

Severity

serious, but I can work around it

Additional Information

No response

frederichoule avatar Aug 10 '23 13:08 frederichoule

As this was fixed with 26477cf9e76c636bad2a3fc46cd2deaf203d6f1c, this can now be closed

LorenzoLeonardini avatar Jan 09 '24 20:01 LorenzoLeonardini