Files
it-tools/src/base-url.e2e.spec.ts
T
0a1f5dc450 feat(docker): serve the app from any subpath with a runtime BASE_URL (#565)
* feat(docker): serve the app from any subpath with a runtime BASE_URL

BASE_URL was a build argument, so hosting under a subfolder meant building
your own image (or pulling the separate baseurl-it-tools tag, which is only
ever right for /it-tools/). Make it a runtime setting instead, so the regular
image works anywhere:

    docker run -e BASE_URL=/it-tools/ ghcr.io/sharevb/it-tools:latest

The build is now path-agnostic. Vite's base is relative, so hashed assets and
lazy chunks resolve against the chunk that imports them, and the single
absolute anchor left in the output is a `<base href="/">` injected into
index.html. nginx rewrites that one tag per request (sub_filter) from the
normalised BASE_URL, and the app reads its base back from it at runtime
(src/utils/base-url.ts) for the router and for every URL it builds into
public/ -- import.meta.env.BASE_URL is meaningless in a relative build.

Also handled:

- both reverse-proxy styles: the prefix may reach the container (stripped by
  the rewrite) or be stripped by the proxy first (nothing to do). The assets
  location matches with or without it, so a missing chunk is still a 404
  rather than the SPA shell.
- `/it-tools` redirects to `/it-tools/`, with a relative Location so the
  scheme of the proxy hop does not leak into it.
- the PWA: manifest URLs are relative to the manifest, workbox precache
  entries relative to the service worker, and the worker is registered
  against the runtime base rather than the build-time one.
- BASE_URL is normalised (`it-tools`, `/it-tools`, `/it-tools/` all work) and
  rejected if it is not a plain path, since it lands in an HTML attribute and
  in an nginx regex.

Defaults are unchanged: with BASE_URL unset the rendered config and the
served page are what they were, except that index.html loses ETag/Last-Modified
to sub_filter. On a read-only filesystem the template cannot be re-rendered,
so BASE_URL is ignored there and the container now says so, like it already
had to for PORT.

Building with --build-arg BASE_URL still works but only moves the image
default; the baseurl-it-tools tag is now just latest with that default.

Closes sharevb/it-tools#403

* fix(docker): restore the PWA update reload, escape BASE_URL in the nginx regexes

Follow-up from review of the runtime BASE_URL change.

- registerSW() in autoUpdate mode reloaded the page when a newly deployed
  worker took over (workbox-window's `activated` handler); hand-rolling the
  registration dropped that, so a tab kept running the previous bundle until
  it navigated. Reimplemented on `controllerchange`, guarded so a first
  install -- which also claims the page -- does not reload. Verified by
  counting document loads across an install and a simulated deploy: 1 load on
  first visit, exactly 1 reload when a new worker takes over.
- The comment justifying the hand-rolled registration was wrong: register()
  does resolve a relative URL against `<base href>`. The real reason is
  workbox-window's own urlsMatch(), which resolves against location.href, so
  a relative sw URL misidentifies the worker on a route deeper than one
  segment. Comment now says that.
- BASE_URL allows `.`, which is a metacharacter in the two nginx regexes it
  is spliced into: `/it.tools/` also matched `/itXtools/`. The entrypoint now
  exports regex-escaped forms for those, keeping the literal value for the
  sub_filter replacement and the redirect target.
- Dropped `$uri/` from try_files. Nothing in the build is a directory with an
  index, so the only thing it ever produced was nginx's trailing-slash
  redirect -- computed after the prefix rewrite, so `/it-tools/figlet-fonts`
  answered `301 /figlet-fonts/` and bounced the browser out of the app.
- The sub_filter comment claimed index.html was the only response losing
  ETag/Last-Modified; public/visualsubnetcalc/calc.html is HTML too and is
  equally affected. Comment corrected.
- README: in the prefix-stripping proxy setup, `/it-tools` without the
  trailing slash never reaches the container, so the proxy has to redirect it
  (as the sample does). Said so.
- The new e2e test reloaded a page that had just started pulling in a tool's
  chunks; WebKit cancelled the load ~1 run in 3 (the app reloads itself on an
  aborted chunk fetch). It opens the URL in a second tab instead: 8/8 on
  WebKit, 3/3 browsers green.

* fix(build): validate BASE_URL before it reaches the <base href>

From Copilot's review of #10.

The container validates its runtime BASE_URL, but the build-time one went
straight into an HTML attribute unchecked: a value carrying a quote rewrote
the tag around it, and one carrying a space or `..` quietly produced a page
that loads from the wrong place. Apply the same rule the entrypoint does --
a plain path of unreserved characters -- and fail the build otherwise.

Also: "can not" -> "cannot" in the read-only filesystem warning.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-19 22:16:54 +02:00

169 lines
6.6 KiB
TypeScript

import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
import { createServer } from 'node:http';
import type { Server } from 'node:http';
import { extname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from '@playwright/test';
// The app is built once, for no particular path, and told where it lives at request time.
// This exercises that: a server that mounts `dist` under a subfolder the way the container
// does -- rewrite the one `<base href>` in index.html, serve everything else from the same
// files -- and then checks the app actually works from there.
//
// See nginx.conf (the real thing), vite.config.ts (`base` and the baseHref plugin) and
// src/utils/base-url.ts (how the app reads it back).
const BASE_URL = '/it-tools/';
const DIST = resolve(fileURLToPath(new URL('.', import.meta.url)), '../dist');
const CONTENT_TYPES: Record<string, string> = {
'.css': 'text/css',
'.html': 'text/html',
'.ico': 'image/x-icon',
'.js': 'text/javascript',
'.json': 'application/json',
'.md': 'text/markdown',
'.mjs': 'text/javascript',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.wasm': 'application/wasm',
'.webmanifest': 'application/manifest+json',
};
function resolveInDist(pathname: string): string | undefined {
const candidate = join(DIST, normalize(pathname));
if (!candidate.startsWith(DIST) || !existsSync(candidate) || !statSync(candidate).isFile()) {
return undefined;
}
return candidate;
}
function serveDistUnder(base: string): Promise<{ server: Server; origin: string }> {
// What nginx.conf does with sub_filter, on every HTML response rather than only on the
// SPA fallback: the service worker precaches index.html by fetching it, and it has to
// get the same document a navigation would.
const withBaseHref = (html: string) => html.replace('<base href="/">', `<base href="${base}">`);
const indexHtml = withBaseHref(readFileSync(join(DIST, 'index.html'), 'utf-8'));
const server = createServer((request, response) => {
const { pathname } = new URL(request.url ?? '/', 'http://localhost');
// Everything below the mount point, with the prefix dropped -- the reverse proxy in
// front of a container may or may not have stripped it already, so nginx.conf copes
// with both and so does this.
const path = decodeURIComponent(pathname.startsWith(base) ? pathname.slice(base.length - 1) : pathname);
const asset = path.match(/^\/(?:.*\/)?assets\/(.+)$/);
const file = asset ? resolveInDist(`/assets/${asset[1]}`) : resolveInDist(path);
if (!file) {
// A missing hashed chunk is a 404, not the SPA shell: serving index.html in its
// place turns a plain 404 into an opaque MIME error in the browser.
if (asset) {
response.writeHead(404).end();
return;
}
response.writeHead(200, { 'content-type': 'text/html' }).end(indexHtml);
return;
}
response.writeHead(200, {
'content-type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream',
// Same headers the container sets; the WebAssembly-backed tools need them.
'cross-origin-opener-policy': 'same-origin',
'cross-origin-embedder-policy': 'require-corp',
});
if (extname(file) === '.html') {
response.end(withBaseHref(readFileSync(file, 'utf-8')));
return;
}
createReadStream(file).pipe(response);
});
return new Promise((done) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address();
const port = typeof address === 'object' && address !== null ? address.port : 0;
done({ server, origin: `http://127.0.0.1:${port}` });
});
});
}
test.describe('Deployment under a subfolder', () => {
let server: Server;
let origin: string;
test.beforeAll(async () => {
({ server, origin } = await serveDistUnder(BASE_URL));
});
test.afterAll(async () => {
await new Promise((done) => server.close(done));
});
test('loads the app, and everything it asks for, from the subfolder', async ({ page }) => {
const notFound: string[] = [];
page.on('response', (response) => {
if (response.status() === 404 && response.url().startsWith(origin)) {
notFound.push(response.url());
}
});
await page.goto(`${origin}${BASE_URL}`);
await expect(page).toHaveTitle(/IT Tools/);
// Router links carry the subfolder, so navigating inside the app stays inside it.
await expect(page.locator(`a[href^="${BASE_URL}"]`).first()).toBeVisible();
expect(notFound).toEqual([]);
});
test('serves a deep link, whose assets are one directory further down', async ({ page }) => {
// The interesting case for a relative build: index.html is served for a path that is
// not the app root, so `./assets/...` would resolve one level too deep without the
// `<base href>` the server injected.
await page.goto(`${origin}${BASE_URL}json-to-yaml-converter`);
await expect(page).toHaveTitle('JSON to YAML converter - IT Tools');
// Reaching the tool at all means its lazily imported chunk was resolved correctly.
await page.getByTestId('input').fill('{"foo":"bar"}');
expect((await page.getByTestId('area-content').innerText()).trim()).toEqual('foo: bar');
});
test('keeps the subfolder when navigating and reloading', async ({ page }) => {
await page.goto(`${origin}${BASE_URL}`);
const homeTitle = await page.title();
await page.locator('a.it-tool-link').first().click();
// The router was handed the runtime base, so an in-app navigation writes a URL that
// still points inside the subfolder -- and reloading it lands back on the same tool
// instead of on the app root or a 404.
await expect(page).not.toHaveURL(`${origin}${BASE_URL}`);
expect(page.url().startsWith(`${origin}${BASE_URL}`)).toBe(true);
await expect(page).not.toHaveTitle(homeTitle);
const url = page.url();
const title = await page.title();
// Then load that URL from scratch, the way someone pasting the link would: it has to
// come back as the same tool rather than as the app root or a 404. In a second tab
// rather than by reloading this one -- navigating a page that has just pulled in a
// tool's chunks races with those requests, and the app answers an aborted chunk load
// by reloading itself (the vite:preloadError handler in src/main.ts), which cancels
// the navigation the test is waiting on.
const fresh = await page.context().newPage();
await fresh.goto(url);
await expect(fresh).toHaveURL(url);
await expect(fresh).toHaveTitle(title);
await fresh.close();
});
});