forge
Explore
Log in

Don't you dare go Hollow

The swap settles the URL before it runs the new page's scripts

Browse files at this commit

019cbd0b00dce3829d7f439291d73e08780a35d2Ahmet Kaan GümüşParent: d75fca7
  • fix
    • the swap settles the URL before it runs the new page's scripts
Show full message
🐛 fix(nav): the swap settles the URL before it runs the new page's scripts

`swap()` replaced the body — which re-executes the swapped-in page's
inline scripts — and only then rewrote the address bar. `logs.rs`'s fit
script reads `location.href` and reloads through it, so it read the page
the browser had just left: pressing Logs painted the page and then
hard-navigated back to the board a couple of hundred milliseconds later.
The second press worked, its `sessionStorage` fit guard now set, which is
why this looked like a render glitch rather than a bug.

History and the `<html>` attributes now move before the body swap, and
the link handler pushes through `swap` instead of after it.

Two guards, both mutation-checked against the old ordering: an ordering
assertion over the served script in `tests/http.rs`, and `tests/browser/`
— a real Chromium that presses Logs twice, the second press having to be
a swap with no document load. Playwright stays out of the repo; the
runner installs it once into `~/.cache/izlek/browser-tests`.
crates/izlek-web/src/layout.rsmodified+16 -11
@@ -142,6 +142,11 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang:
142142 /// arrive with the swap because the redirect URL's query params rendered
143143 /// them server-side; `history.replaceState` keeps the address bar honest.
144144 ///
145+/// The address bar and the `<html>` attributes are rewritten *before* the
146+/// new body's scripts run, never after: a swapped-in script that reads
147+/// `location.href` (the log-fit reload in `logs.rs`) would otherwise read
148+/// the page it just replaced and hard-navigate back to it.
149+///
145150 /// Swapped-in `<script>` nodes are inert (parser-inserted only), so
146151 /// `swap()` re-creates each one as a fresh element, which runs it; every
147152 /// emitted script carries a one-shot `window.__izlek*` guard, so that
@@ -163,8 +168,8 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang:
163168 ///
164169 /// Ordinary same-origin links get the same treatment: a delegated capture
165170 /// click listener — registered after the close/scrim one, and skipped when
166-/// that one already `preventDefault`ed — fetches the href and swaps it in,
167-/// then `history.pushState`s, so board cards and file chips no longer
171+/// that one already `preventDefault`ed — fetches the href and swaps it in
172+/// under a `history.pushState`, so board cards and file chips no longer
168173 /// reload the page. Raw `/files/` byte routes, `download`/`target`/
169174 /// `data-hard` links and modified clicks (ctrl/meta/shift/alt, non-left
170175 /// button) stay browser-native. `popstate` replays the same fetch without
@@ -181,9 +186,16 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
181186 document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \
182187 document.dispatchEvent(new Event('izlek:wire')); \
183188 } \
184- function swap(html, url, fresh) { \
189+ function swap(html, url, fresh, push) { \
185190 var doc = new DOMParser().parseFromString(html, 'text/html'); \
186191 var x = window.scrollX, y = window.scrollY; \
192+ var root = doc.documentElement; \
193+ if (root.getAttribute('lang')) { document.documentElement.setAttribute('lang', root.getAttribute('lang')); } \
194+ if (root.hasAttribute('data-theme')) { document.documentElement.setAttribute('data-theme', root.getAttribute('data-theme')); } \
195+ else { document.documentElement.removeAttribute('data-theme'); } \
196+ if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \
197+ else { document.documentElement.removeAttribute('data-ui'); } \
198+ if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \
187199 document.body.replaceChildren(); \
188200 while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \
189201 document.body.querySelectorAll('script').forEach(function (old) { \
@@ -192,13 +204,6 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
192204 live.textContent = old.textContent; \
193205 old.replaceWith(live); \
194206 }); \
195- var root = doc.documentElement; \
196- if (root.getAttribute('lang')) { document.documentElement.setAttribute('lang', root.getAttribute('lang')); } \
197- if (root.hasAttribute('data-theme')) { document.documentElement.setAttribute('data-theme', root.getAttribute('data-theme')); } \
198- else { document.documentElement.removeAttribute('data-theme'); } \
199- if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \
200- else { document.documentElement.removeAttribute('data-ui'); } \
201- if (url) { history.replaceState(null, '', url); } \
202207 window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \
203208 wire(); \
204209 } \
@@ -298,7 +303,7 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
298303 if (!href || href.charAt(0) !== '/' || href.indexOf('/files/') === 0) { return; } \
299304 e.preventDefault(); \
300305 fetch(href).then( \
301- function (r) { return r.text().then(function (t) { swap(t, null, true); history.pushState(null, '', r.url); }); }, \
306+ function (r) { return r.text().then(function (t) { swap(t, r.url, true, true); }); }, \
302307 function () { window.location.href = href; } \
303308 ); \
304309 }, true); \
crates/izlek-web/tests/browser/run.shadded+64 -0
@@ -0,0 +1,64 @@
1+#!/usr/bin/env bash
2+# Runs the browser checks against a throwaway İzlek: its own database, its
3+# own port, torn down after. Never touches config/izlek.toml or izlek.db —
4+# the server reads its config from the working directory, so it is given a
5+# directory of its own.
6+#
7+# crates/izlek-web/tests/browser/run.sh
8+#
9+# Playwright is not a dependency of this repo and never will be: İzlek has
10+# no node in it. It is installed once into ~/.cache/izlek/browser-tests
11+# (Chromium included, ~120MB) the first time this runs, and found there
12+# every time after. IZLEK_PLAYWRIGHT and PLAYWRIGHT_BROWSERS_PATH override
13+# that if the install belongs somewhere else.
14+set -euo pipefail
15+
16+repo=$(cd "$(dirname "$0")/../../../.." && pwd)
17+port=${IZLEK_BROWSER_PORT:-7791}
18+work=$(mktemp -d)
19+shots=${SHOT_DIR:-$work}
20+
21+cleanup() {
22+ [[ -n ${server:-} ]] && kill "$server" 2>/dev/null || true
23+ rm -rf "$work"
24+}
25+trap cleanup EXIT
26+
27+# The one-time Playwright install, kept out of the repo and out of the
28+# session scratchpad so it survives both.
29+home=${IZLEK_BROWSER_HOME:-${XDG_CACHE_HOME:-$HOME/.cache}/izlek/browser-tests}
30+export PLAYWRIGHT_BROWSERS_PATH=${PLAYWRIGHT_BROWSERS_PATH:-$home/browsers}
31+export IZLEK_PLAYWRIGHT=${IZLEK_PLAYWRIGHT:-$home/node_modules/playwright/index.mjs}
32+if [[ ! -f $IZLEK_PLAYWRIGHT ]]; then
33+ echo "installing playwright into $home (once)"
34+ mkdir -p "$home"
35+ # npm's own postinstall would drag in headed Chromium and ffmpeg — 390MB
36+ # nothing here launches. The shell build is the whole need.
37+ (cd "$home" && npm init -y > /dev/null &&
38+ PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install playwright > /dev/null)
39+ (cd "$home" && npx playwright install --only-shell chromium)
40+fi
41+
42+cargo build --manifest-path "$repo/Cargo.toml" -p izlek-web
43+
44+mkdir -p "$work/config"
45+printf 'database = "izlek.db"\nlisten = "127.0.0.1:%s"\n' "$port" > "$work/config/izlek.toml"
46+
47+# Started from $work so it claims that directory's config and database, and
48+# backgrounded here rather than down a pipeline so $! is the server itself —
49+# a stale pid leaves the port bound and the next run silently talks to the
50+# old process.
51+(cd "$work" && exec "$repo/target/debug/izlek-web" > "$work/server.log" 2>&1) &
52+server=$!
53+
54+for _ in $(seq 1 60); do
55+ curl -sf "http://127.0.0.1:$port/healthz" > /dev/null && break
56+ sleep 0.25
57+done
58+if ! curl -sf "http://127.0.0.1:$port/healthz" > /dev/null; then
59+ echo "the server never came up on $port:"
60+ cat "$work/server.log"
61+ exit 1
62+fi
63+
64+SHOT_DIR="$shots" node "$repo/crates/izlek-web/tests/browser/soft-nav.mjs" "http://127.0.0.1:$port"
crates/izlek-web/tests/browser/soft-nav.mjsadded+139 -0
@@ -0,0 +1,139 @@
1+// The one check `cargo test` cannot make: that the soft swap actually holds
2+// in a browser. `tests/http.rs` asserts the shape of the script İzlek serves;
3+// only a real engine runs it.
4+//
5+// Guards the URL-lag class. `swap()` (`src/layout.rs`) replaces the body,
6+// which re-executes the new page's inline scripts; `logs.rs`'s fit script
7+// reads `location.href` and reloads through it. While the address bar was
8+// rewritten after the swap rather than before, clicking Logs painted the
9+// page and then hard-navigated back to the board a few hundred milliseconds
10+// later — one press lost, every first visit.
11+//
12+// Wants a server on a throwaway database with the workspace unclaimed:
13+//
14+// node crates/izlek-web/tests/browser/soft-nav.mjs http://127.0.0.1:7791
15+//
16+// Playwright lives outside the repo — İzlek has no node dependency and
17+// gains none here. Point PLAYWRIGHT_BROWSERS_PATH at the browser download
18+// and IZLEK_PLAYWRIGHT at the installed package (ESM resolves imports from
19+// this file's directory, not the working one, so a bare name will not do).
20+const { chromium } = await import(process.env.IZLEK_PLAYWRIGHT || 'playwright');
21+
22+const base = process.argv[2] || 'http://127.0.0.1:7791';
23+const shots = process.env.SHOT_DIR || '.';
24+const failures = [];
25+const note = (line) => console.log(line);
26+
27+const browser = await chromium.launch();
28+const ctx = await browser.newContext();
29+const page = await ctx.newPage();
30+const errors = [];
31+page.on('pageerror', (e) => errors.push('PE ' + e.message));
32+page.on('console', (m) => {
33+ if (m.type() === 'error') errors.push('CON ' + m.text());
34+});
35+// Every full document load, soft-nav's whole point being that there is
36+// exactly one of them: the claim.
37+const loads = [];
38+page.on('load', () => loads.push(page.url()));
39+
40+// The workspace is unclaimed, so the first page is the claim form and
41+// filling it signs the admin in.
42+await page.goto(base + '/', { waitUntil: 'networkidle' });
43+await page.fill('input[name="display_name"]', 'Ada Lovelace');
44+await page.fill('input[name="email"]', 'ada@izlek.sh');
45+await page.fill('input[name="password"]', 'correct horse battery staple');
46+await Promise.all([
47+ page.waitForLoadState('networkidle'),
48+ page.click('button[type="submit"]'),
49+]);
50+if (!/\/$/.test(new URL(page.url()).pathname)) {
51+ failures.push(`claiming the workspace landed on ${page.url()}`);
52+}
53+await page.screenshot({ path: `${shots}/board.png`, fullPage: true });
54+
55+// Two visits, because they exercise different halves. The first runs the
56+// fit script for real: it sets its row cookie and reloads *itself*, which
57+// is by design — what must never happen is a load of any other URL, which
58+// is exactly what the URL-lag bug produced. The second visit finds the fit
59+// guard already set, so nothing reloads and the swap has to carry the page
60+// on its own.
61+async function visitLogs(label, { swapOnly }) {
62+ const before = loads.length;
63+ // Survives a swap (the document is never replaced) and dies with any
64+ // real navigation, which is the whole question being asked.
65+ await page.evaluate(() => {
66+ window.__softNavProbe = 'alive';
67+ });
68+
69+ const logs = page.locator('a[href="/logs"]').first();
70+ if (!(await logs.count())) {
71+ failures.push(`${label}: no /logs link on the board`);
72+ return;
73+ }
74+ await logs.click();
75+ await page
76+ .waitForFunction(() => location.pathname === '/logs', { timeout: 5000 })
77+ .catch(() => failures.push(`${label}: the Logs click never reached /logs`));
78+ // The bounce took ~200ms; a second and a half is that window and then
79+ // some. Sleeping is the measurement — there is no event for "the page
80+ // did not go anywhere".
81+ await page.waitForTimeout(1500);
82+
83+ const where = new URL(page.url()).pathname;
84+ if (where !== '/logs') {
85+ failures.push(
86+ `${label}: bounced off /logs to ${where} — the swap ran the new page's scripts under the old URL`,
87+ );
88+ }
89+ const strayed = loads
90+ .slice(before)
91+ .map((u) => new URL(u).pathname)
92+ .filter((p) => p !== '/logs');
93+ if (strayed.length) {
94+ failures.push(`${label}: loaded ${strayed.join(', ')} instead of staying on Logs`);
95+ }
96+ if (swapOnly) {
97+ if (loads.length > before) {
98+ failures.push(`${label}: reloaded ${loads.length - before} time(s); the fit guard was already set, so this had to be a swap`);
99+ }
100+ const probe = await page.evaluate(() => window.__softNavProbe || null);
101+ if (probe !== 'alive') {
102+ failures.push(`${label}: the document was replaced — Logs arrived by a real navigation, not a swap`);
103+ }
104+ }
105+ const body = await page.textContent('body');
106+ if (!body || body.trim().length < 40) {
107+ failures.push(`${label}: the logs page rendered blank`);
108+ }
109+ await page.screenshot({ path: `${shots}/logs-${label}.png`, fullPage: true });
110+}
111+
112+// First press: the fit script is allowed to reload itself, nothing else.
113+await visitLogs('first', { swapOnly: false });
114+
115+// Home again, then press Logs a second time — the press that used to be
116+// the only one that worked, and now has to be a pure swap.
117+await page.locator('a[href="/"]').first().click();
118+await page
119+ .waitForFunction(() => location.pathname === '/', { timeout: 5000 })
120+ .catch(() => failures.push('the board link never came home'));
121+await page.waitForTimeout(500);
122+await visitLogs('second', { swapOnly: true });
123+
124+// Back has to come home the same way.
125+await page.goBack();
126+await page.waitForTimeout(800);
127+if (new URL(page.url()).pathname !== '/') {
128+ failures.push(`back from Logs landed on ${new URL(page.url()).pathname}`);
129+}
130+
131+await browser.close();
132+
133+note(`document loads ${loads.map((u) => new URL(u).pathname).join(' → ')} · page errors ${errors.length ? errors.join(' | ') : 'none'}`);
134+if (errors.length) failures.push(`page errors: ${errors.join(' | ')}`);
135+if (failures.length) {
136+ for (const f of failures) note('FAIL ' + f);
137+ process.exit(1);
138+}
139+note('PASS soft-nav holds: Logs stayed put on both presses, the second by swap alone, and back came home');
crates/izlek-web/tests/http.rsmodified+55 -0
@@ -1964,6 +1964,61 @@ async fn the_rules_and_logs_pages_get_the_shared_escape_script() {
19641964 );
19651965 }
19661966
1967+/// The soft swap settles the address bar before it runs the swapped-in
1968+/// page's scripts, never after. `logs.rs`'s fit script reloads through
1969+/// `location.replace(location.href)`; while the link handler pushed the
1970+/// new URL only after `swap()` had re-executed scripts, that read the
1971+/// page the browser had just left, so clicking Logs painted the page and
1972+/// hard-navigated back to the board a few hundred milliseconds later.
1973+/// Ordering inside `swap` is the whole fix, so ordering is what is
1974+/// asserted, together with the hazard that makes it matter.
1975+#[tokio::test]
1976+async fn the_soft_swap_rewrites_the_url_before_the_new_pages_scripts_run() {
1977+ let app = App::open().await;
1978+ let cookie = admin(&app).await;
1979+
1980+ let page = app.get("/", Some(&cookie)).await;
1981+ let html = String::from_utf8_lossy(&page.bytes);
1982+ let (_, after) = html
1983+ .split_once("function swap(html, url, fresh, push)")
1984+ .unwrap_or_else(|| panic!("no soft-nav swap on the board page: {html}"));
1985+ let body = after
1986+ .split_once("window.__izlekGo")
1987+ .unwrap_or_else(|| panic!("swap runs past the end of the script: {after}"))
1988+ .0;
1989+ let rewrite = body
1990+ .find("history[")
1991+ .unwrap_or_else(|| panic!("swap no longer rewrites history: {body}"));
1992+ let run = body
1993+ .find("document.body.replaceChildren()")
1994+ .unwrap_or_else(|| panic!("swap no longer replaces the body: {body}"));
1995+ assert!(
1996+ rewrite < run,
1997+ "swap runs the new page's scripts before the URL is settled: {body}"
1998+ );
1999+
2000+ // Every caller hands `swap` the response URL. A `null` here is the
2001+ // old shape: the address bar lagged the body by one navigation.
2002+ assert!(
2003+ html.contains("swap(t, r.url, true, true)"),
2004+ "the link handler no longer pushes through swap: {html}"
2005+ );
2006+ assert!(
2007+ !html.contains("swap(t, null"),
2008+ "a swap still runs the new page's scripts under the old URL: {html}"
2009+ );
2010+
2011+ // The hazard itself: a swapped-in script that reads `location.href`
2012+ // on load. Were this to go, the ordering above would still be right
2013+ // but would guard nothing.
2014+ let logs = app.get("/logs", Some(&cookie)).await;
2015+ let logs_html = String::from_utf8_lossy(&logs.bytes);
2016+ assert!(
2017+ logs_html.contains("location.replace(location.href)"),
2018+ "the log-fit reload is gone: {logs_html}"
2019+ );
2020+}
2021+
19672022 #[tokio::test]
19682023 async fn signing_out_stops_the_session_being_worth_anything() {
19692024 let app = App::open().await;