From c199f1b9c97b288e3c256656d4f1982c9bc4cc45 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Tue, 17 Nov 2026 12:27:17 +0000 Subject: [PATCH 1/2] Prepend a constant replay:// marker to every ZIM path wombat.js computes its own replay prefix ("wb_rel_prefix") by subtracting the serving origin from the page's own URL. When a ZIM is served with no extra "collection" path segment (e.g. a bare kiwix.app/), that subtraction used to leave an empty or single-"/" prefix, degenerating a regex used by wombat.js's innerHTML/outerHTML getters into matching (and deleting) any /text/ span anywhere in the page. The same degenerate prefix also caused rewriteUrl to treat any already-relative URL as "already rewritten" (silently skipping genuine rewriting), and rewriteCookie to strip the first "/" found anywhere in a cookie value instead of a real prefix. Fixes openzim/zimit#589. normalize() now prepends REPLAY_MARKER ("replay://") to every ZIM path, and wombatSetup.js's urlRewriteFunction does the same, so wb_rel_prefix can never again collapse to something with zero discriminating power, by construction. ZimPath.check_validity() stays lenient (accepts both marked and unmarked values), since one pre-existing non-normalize() ZimPath construction (_zim_static/__wb_module_decl.js) is never itself an HTML document computing a replay prefix and doesn't need the marker. get_document_uri() strips the marker from both the article and item paths before computing the relative href: since both are normally marked identically, it cancels out as a shared leading segment and never needs to be reintroduced into the computed href. hasAlreadyBeenRewritten's "looks like a hostname" heuristic for detecting an already-rewritten relative link is unaffected (such a link never carries the marker, since it cancels out the same way on the JS side). Added a separate isAlreadyPrefixed() check for the different case of a fully-prefixed absolute URL re-entering urlRewriteFunction (e.g. read back from img.src and reassigned elsewhere), which the existing prefix-unwrapping logic would otherwise mangle by re-adding a scheme in front of the embedded marker. head_insert.html computes its own replay prefix by subtracting the rendered article path's length from the current document's real URL; it now strips a leading REPLAY_MARKER from that path first, so the marker stays part of the computed prefix instead of being subtracted away. A companion fix in warc2zim's quote() call (which renders that template variable) is needed for the marker's colon to survive unescaped end to end; see the linked warc2zim PR. --- CHANGELOG.md | 1 + javascript/src/wombatSetup.js | 80 +++---- javascript/test/wombatUrlRewriting.js | 123 +++++----- .../rewriting/templates/head_insert.html | 14 +- src/zimscraperlib/rewriting/url_rewriting.py | 46 +++- tests/rewriting/test_html_rewriting.py | 43 ++-- tests/rewriting/test_js_rewriting.py | 3 +- tests/rewriting/test_url_rewriting.py | 219 +++++++++++------- 8 files changed, 323 insertions(+), 206 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e516d078..d7943724 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Polyfill `crypto.subtle.digest()` (SHA-1/SHA-256) when missing in a non-secure context (#393) - `ArticleUrlRewriter.normalize()` no longer decodes a percent-encoded `/` (`%2F`) in the path into a literal `/`, fixing a content collision between e.g. `/foo%2Fbar` (one segment, containing a literal `/`) and `/foo/bar` (two segments), which used to normalize to the same ZIM path (#396) - `ArticleUrlRewriter.escape_dot_segments()` now also escapes a literal `_.`/`_..` (and further escaped forms like `__.`/`__..`) segment with one more leading `_`, fixing a content collision with the escaped form of an actual `.`/`..` dot-segment, which used to normalize to the same ZIM path (#396) +- `ArticleUrlRewriter.normalize()` now prefixes every ZIM path with a constant `replay://` marker, and `wombatSetup.js`'s `urlRewriteFunction`/`head_insert.html` do the same, fixing wombat.js computing an empty or single-`/` replay prefix ("`wb_rel_prefix`") for a ZIM served with no extra "collection" path segment (e.g. a bare `kiwix.app/`), which corrupted any `innerHTML`/`outerHTML` read on the page by deleting arbitrary `/text/` spans, and caused related, quieter bugs in `rewriteUrl`/`rewriteCookie` (#396, openzim/zimit#589) ### Changed diff --git a/javascript/src/wombatSetup.js b/javascript/src/wombatSetup.js index 77976c46..ad932bc8 100644 --- a/javascript/src/wombatSetup.js +++ b/javascript/src/wombatSetup.js @@ -214,6 +214,15 @@ if (typeof crypto !== 'undefined' && typeof crypto.subtle === 'undefined') { crypto.subtle = { digest: digestPolyfill }; } +// A constant marker prepended to every ZIM path by urlRewriteFunction, mirroring +// Python's `REPLAY_MARKER` in `zimscraperlib.rewriting.url_rewriting`. It gives +// wombat.js a non-empty, non-degenerate path segment to compute its own +// replay-prefix detection from, fixing a case where a ZIM served with no extra +// "collection" path segment (e.g. bare `kiwix.app/`) made wombat.js's +// `wb_rel_prefix` degenerate to `''`/`'/'`, corrupting any `innerHTML`/`outerHTML` +// read on the page (webrecorder/wombat, reported as openzim/zimit#589). +export const REPLAY_MARKER = 'replay://'; + export function applyFuzzyRules(path) { // Apply fuzzy rules to simplify the ZIM path. First matching rule is applied and // result is immediately returned @@ -241,6 +250,19 @@ export function escapeDotSegments(path) { .join('/'); } +export function isAlreadyPrefixed(url) { + // REPLAY_MARKER is a constant marker we prepend to every ZIM path (see + // urlRewriteFunction below), so any URL containing it is unambiguously an + // already-rewritten, fully-prefixed absolute URL (e.g. one read back from + // `img.src` and reassigned elsewhere): original web content cannot + // coincidentally produce it. A statically-rewritten *relative* link never + // contains it, since the marker is a shared prefix between the current + // document and the link's target, and so is absent from the relative + // reference computed between them (see `hasAlreadyBeenRewritten` for that + // case instead). + return url.includes(REPLAY_MARKER); +} + export function hasAlreadyBeenRewritten( original_absolute_url, orig_url, @@ -302,6 +324,15 @@ export function urlRewriteFunction( // Transform URL which might be an object (detected on Chromium browsers at least) url = String(url); + // Detect if url is already a fully-prefixed, already-rewritten absolute URL and + // return as-is in such a case. This must run before any other processing below: + // in particular, the prefix-unwrapping a few lines down would otherwise mangle + // such a URL (e.g. one read back from `img.src` and reassigned elsewhere) by + // re-adding a scheme in front of its embedded REPLAY_MARKER. + if (isAlreadyPrefixed(url)) { + return url; + } + // Special stuff which is not really a URI but exists in the wild if (['#', '{', '*'].includes(url.substring(0, 1))) return url; @@ -336,48 +367,16 @@ export function urlRewriteFunction( // present ; current URL does not allow to do it easily const original_absolute_url = URI.resolve(orig_url, url); - // Detect if url has probably already been rewritten and return as-is in such a case + // Detect if url has probably already been rewritten and return as-is in such a + // case. Unlike isAlreadyPrefixed above, this specifically catches an + // already-rewritten *relative* link (e.g. a cross-host link produced by + // get_document_uri()): such a link never contains REPLAY_MARKER, since the + // marker is a shared prefix between the current document and the link's target + // and so cancels out of the relative reference computed between them. if (hasAlreadyBeenRewritten(original_absolute_url, orig_url, uri, url)) { return url; } - // Detect (with a heuristic) that the path is most probably already rewritten and - // must be kept as-is. We just need to detect relative links (all statically rewritten - // links are relative) and contains a path including the hostname (which cannot be - // joined with the orig_url since if it includes the hostname, it means it is in - // another hostname than orig_url and will hence go one level too high in the path - // hierarchy, hence working only on ZIM paths / relative links). - // The heurisitic is: - // - the link must be relative and start by going at least one level up - // - the first non relative part of the path (i.e. not . or ..) looks like a hostname - // (i.e. it contains a dot) - // - the relative link, when merged with orig_url, is going exactly one "path level" - // too high in the hierarchy - if (typeof uri.scheme == 'undefined' && url.startsWith('../')) { - const urlParts = url.split('/'); - const original_absolute_url1 = URI.resolve( - orig_url, - urlParts.slice(1).join('/'), - ); - const original_absolute_url2 = URI.resolve( - orig_url, - urlParts.slice(2).join('/'), - ); - // detect that relative link is going exactly one "path level" too high - if ( - original_absolute_url1 == original_absolute_url && - original_absolute_url2 != original_absolute_url - ) { - const firstNonRelativePart = urlParts.find((urlPart) => urlPart !== '..'); - // detect that first non relative part of the path looks like a hostname - if (firstNonRelativePart.indexOf('.') > -1) { - // if all 3 conditions are true, then we do not rewrite the link at all, - // otherwise we continue with normal rewritting - return url; - } - } - } - // We now have to transform this absolute URI into a normalized ZIM path entry const absolute_url_parts = URI.parse(original_absolute_url); @@ -420,10 +419,11 @@ export function urlRewriteFunction( // Reencode everything but '/' (we decode it afterwards for simplicity) const finalUrl = prefix + - encodeURIComponent(escapedPath) + encodeURIComponent(REPLAY_MARKER + escapedPath) .replaceAll('%2F', '/') .replaceAll('%3D', '=') - .replaceAll('%2C', ','); + .replaceAll('%2C', ',') + .replaceAll('%3A', ':'); console.debug( 'urlRewriten:\n\t- current_url: ' + diff --git a/javascript/test/wombatUrlRewriting.js b/javascript/test/wombatUrlRewriting.js index 1973922f..5e89b489 100644 --- a/javascript/test/wombatUrlRewriting.js +++ b/javascript/test/wombatUrlRewriting.js @@ -46,7 +46,7 @@ test('simpleContentCompleteUrl', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -63,7 +63,7 @@ test('simpleContentFullUrl', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -80,7 +80,7 @@ test('simpleContentNoScheme', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -97,7 +97,7 @@ test('consecutiveSlashesAreKept', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/a///b', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/a///b', ); }); @@ -120,7 +120,7 @@ test('relativeLinkOnPageWithConsecutiveSlashesKeepsThem', (t) => { undefined, undefined, ), - t.context.prefix + 'www.example.com/path1//other.html', + t.context.prefix + 'replay://www.example.com/path1//other.html', ); }); @@ -137,7 +137,7 @@ test('simpleContentEmptyPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/', ); }); @@ -154,7 +154,7 @@ test('simpleContentNoPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/', ); }); @@ -171,7 +171,7 @@ test('contentWithSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -188,7 +188,7 @@ test('contentWithUTF8CharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%F0%9F%8E%81nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%F0%9F%8E%81nt.txt', ); }); @@ -205,7 +205,7 @@ test('contentWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -222,7 +222,7 @@ test('contentWithSpaceNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%20nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%20nt.txt', ); }); @@ -239,7 +239,7 @@ test('contentWithPlusNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%2Bnt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%2Bnt.txt', ); }); @@ -256,7 +256,7 @@ test('contentWithTilde', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont~nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont~nt.txt', ); }); @@ -273,7 +273,7 @@ test('contentWithHyphen', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont-nt.txt', ); }); @@ -290,7 +290,7 @@ test('contentWithUnderscore', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont_nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont_nt.txt', ); }); @@ -307,7 +307,7 @@ test('contentWithEncodedTilde', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont~nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont~nt.txt', ); }); @@ -324,7 +324,7 @@ test('contentWithEncodedApostrophe', (t) => { undefined, undefined, ), - "http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont'nt.txt", + "http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont'nt.txt", ); }); @@ -341,7 +341,7 @@ test('contentWithEncodedExclamationMark', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont!nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont!nt.txt', ); }); @@ -358,7 +358,7 @@ test('contentWithEncodedQuestionMark', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%3Fnt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%3Fnt.txt', ); }); @@ -375,7 +375,7 @@ test('contentWithEncodedQuestionMarkAndQueryParam', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%3Fnt.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%3Fnt.txt%3Fquery=value', ); }); @@ -392,7 +392,7 @@ test('contentWithEncodedStar', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont*nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont*nt.txt', ); }); @@ -409,7 +409,7 @@ test('contentWithEncodedParentheses', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont()nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont()nt.txt', ); }); @@ -426,7 +426,7 @@ test('contentWithEncodedHyphen1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont-nt.txt', ); }); @@ -443,7 +443,7 @@ test('contentWithEncodedHyphen2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/co%25nt-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/co%25nt-nt.txt', ); }); @@ -460,7 +460,7 @@ test('contentWithEncodedUnderscore', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont_nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont_nt.txt', ); }); @@ -477,7 +477,7 @@ test('contentWithEncodedPeriod', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -494,7 +494,7 @@ test('contentWithSimpleQueryString', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=value', ); }); @@ -513,7 +513,7 @@ test('contentWithQueryStringDotDotSegment', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fcss=../_../prg', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fcss=../_../prg', ); }); @@ -531,7 +531,7 @@ test('contentWithQueryValueRawPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=val%20ue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%20ue', ); }); @@ -553,7 +553,7 @@ test('contentWithQueryValueEncodedPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=val%2Bue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%2Bue', ); }); @@ -570,7 +570,7 @@ test('contentWithSimplePathWithEqualAndComma', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt/query1=value1,param2=value2', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt/query1=value1,param2=value2', ); }); @@ -587,7 +587,7 @@ test('contentWithQueryValueEqualSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=val=eue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val=eue', ); }); @@ -604,7 +604,7 @@ test('contentWithQueryValuePercentSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=val%25eue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%25eue', ); }); @@ -621,7 +621,7 @@ test('contentWithQueryParamPercentSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fque%25ry=valeue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fque%25ry=valeue', ); }); @@ -638,7 +638,7 @@ test('contentWithQueryParamPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fparam=val%20ue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fparam=val%20ue', ); }); @@ -655,7 +655,7 @@ test('fqdnWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.%C3%A9xample.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/content.txt', ); }); @@ -672,7 +672,7 @@ test('fqdnWithSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.%C3%A9xample.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/content.txt', ); }); @@ -689,7 +689,7 @@ test('fqdnWithSpecialCharsEncodedContentWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.%C3%A9xample.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/cont%C3%A9nt.txt', ); }); @@ -706,7 +706,7 @@ test('relSimpleContent1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -723,7 +723,7 @@ test('relSimpleContent2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/path1/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/javascript/content.txt', ); }); @@ -740,7 +740,7 @@ test('relGoingUperThanHost', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -757,7 +757,7 @@ test('relSimpleContent3', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -927,7 +927,7 @@ test('youtubeFuzzyNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=123ah', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=123ah', ); }); @@ -944,10 +944,15 @@ test('youtubeFuzzyEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=12=3ah', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=12=3ah', ); }); +// this specifically exercises isAlreadyPrefixed: without it, the prefix-unwrapping +// a few lines into urlRewriteFunction would mangle this fully-prefixed, already +// REPLAY_MARKER-containing absolute URL by re-adding a scheme in front of the +// marker (producing e.g. 'http://replay://www.example.com/...'), instead of +// recognizing it as already rewritten and returning it untouched test('alreadyRewritenUrlSimple', (t) => { t.is( urlRewriteFunction( @@ -956,12 +961,12 @@ test('alreadyRewritenUrlSimple', (t) => { t.context.originalScheme, t.context.originalUrl, t.context.prefix, - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', undefined, undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -978,7 +983,7 @@ test('alreadyRewritenUrlSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -995,7 +1000,7 @@ test('alreadyRewritenUrlUTF8CharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/cont%F0%9F%8E%81nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%F0%9F%8E%81nt.txt', ); }); @@ -1012,7 +1017,7 @@ test('simpleContentDomainNameInPath1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/www.example.com/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/www.example.com/content.txt', ); }); @@ -1029,7 +1034,7 @@ test('simpleContentDomainNameInPath2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/www.example.com', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/www.example.com', ); }); @@ -1047,7 +1052,7 @@ test('relAlreadyEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=value', ); }); @@ -1152,7 +1157,7 @@ test('relTooUpNotLookingLikeAHostname', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -1176,7 +1181,7 @@ test('relTooUpNotLookingLikeAHostnameRootPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -1200,7 +1205,7 @@ test('relTooUpNotLookingLikeAHostnameEmptyPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', ); }); @@ -1220,7 +1225,7 @@ test('relNotReallyAnotherHostAlreadyRewrittenTooUp', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/anotherhost.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/anotherhost.com/javascript/content.txt', ); }); @@ -1241,7 +1246,7 @@ test('relNotReallyAnotherHostAlreadyRewrittenNotUpEnough', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/www.example.com/anotherhost.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/anotherhost.com/javascript/content.txt', ); }); @@ -1258,7 +1263,7 @@ test('doubleSlash1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/example.com/some/path/http%3A//example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/some/path/http://example.com//some/path', ); }); @@ -1275,7 +1280,7 @@ test('doubleSlash2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/example.com/some/pa%3Fth/http%3A//example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/some/pa%3Fth/http://example.com//some/path', ); }); @@ -1292,6 +1297,6 @@ test('doubleSlash3', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/example.com/so%3Fme/pa%3Fth/http%3A//example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/so%3Fme/pa%3Fth/http://example.com//some/path', ); }); diff --git a/src/zimscraperlib/rewriting/templates/head_insert.html b/src/zimscraperlib/rewriting/templates/head_insert.html index e50392ce..cdf7d60f 100644 --- a/src/zimscraperlib/rewriting/templates/head_insert.html +++ b/src/zimscraperlib/rewriting/templates/head_insert.html @@ -13,12 +13,24 @@ return href.toString(); })(); + // Every ZIM path is prefixed with REPLAY_MARKER (see + // zimscraperlib.rewriting.url_rewriting.REPLAY_MARKER); stripping it from the + // current document's own path before subtracting its length from current_url + // keeps the marker as part of the computed prefix below instead of subtracting + // it away, so wombat.js's own replay-prefix detection ("wb_rel_prefix") can + // never again degenerate to '' or '/' (which corrupted any innerHTML/outerHTML + // read on the page, see openzim/zimit#589) when a ZIM is served with no extra + // "collection" path segment (e.g. a bare `kiwix.app/`). + const path = '{{ path }}'.startsWith(wombatSetup.REPLAY_MARKER) + ? '{{ path }}'.slice(wombatSetup.REPLAY_MARKER.length) + : '{{ path }}'; + const wbinfo = wombatSetup.getWombatInfo( current_url, '{{ orig_host }}', '{{ orig_scheme }}', '{{ orig_url }}', - current_url.substring(0, current_url.length - '{{ path }}'.length), + current_url.substring(0, current_url.length - path.length), ); if (window && window._WBWombatInit) { diff --git a/src/zimscraperlib/rewriting/url_rewriting.py b/src/zimscraperlib/rewriting/url_rewriting.py index eb0d78fc..d2f7fac2 100644 --- a/src/zimscraperlib/rewriting/url_rewriting.py +++ b/src/zimscraperlib/rewriting/url_rewriting.py @@ -30,6 +30,18 @@ . This is valid : "foo/part/file?question=Is there any + here?" . This is NOT valid : "foo/part/file?question%3DIs%20there%20any%20%2B%20here%3F" +Every ZIM path produced by `normalize` is prefixed with the constant `REPLAY_MARKER` +(`"replay://"`), e.g. "example.com/foo" becomes "replay://example.com/foo". wombat.js +computes its own replay-prefix ("wb_rel_prefix") by subtracting the serving origin from +the full URL of the page being served; when a ZIM is served with no extra "collection" +path segment (e.g. a bare `kiwix.app/`), that subtraction used to leave an empty +or single-`/` prefix, which degenerates a regex used by wombat.js's `innerHTML`/ +`outerHTML` getters into matching (and deleting) any `/text/` span anywhere in the page +(reported as openzim/zimit#589). The marker guarantees that prefix can never again be +empty or trivial, by construction. A `ZimPath` may also be built directly from an +unmarked value (see `ZimPath.check_validity`), so the marker is never assumed when +reading a `ZimPath` back, only ever added by `normalize` itself. + A ZIM path must never contain a `.` or `..` path segment: per RFC 3986 these "dot-segments" are resolved away by any URI consumer (including the reader turning a relative link back into an absolute one), so a literal `.` or `..` coming from the @@ -90,6 +102,14 @@ class AdditionalRule: for rule in FUZZY_RULES ] +# A constant marker prepended to every ZIM path by `normalize()`. It gives wombat.js a +# non-empty, non-degenerate path segment to compute its own replay-prefix detection +# from (see `ArticleUrlRewriter.normalize` for the full rationale), fixing a case where +# a ZIM served with no extra "collection" path segment (e.g. bare `kiwix.app/`) +# made wombat.js's `wb_rel_prefix` degenerate to `''`/`'/'`, corrupting any +# `innerHTML`/`outerHTML` read on the page (webrecorder/wombat, reported as +# openzim/zimit#589). +REPLAY_MARKER = "replay://" _ENCODED_SLASH_RX = re.compile(r"%2f", re.IGNORECASE) @@ -225,6 +245,10 @@ class ZimPath: """A utility class representing a ZIM path, usefull to pass this data around Includes a basic validation, ensuring that path does start with scheme, hostname,... + + A value produced by `ArticleUrlRewriter.normalize` is prefixed with `REPLAY_MARKER`, + but a `ZimPath` may also be built directly from an unmarked value (e.g. a static + asset path not derived from an HTTP URL), so `check_validity` accepts both. """ def __init__(self, value: str) -> None: @@ -249,7 +273,7 @@ def value(self) -> str: @classmethod def check_validity(cls, value: str) -> None: - parts = urlsplit(value) + parts = urlsplit(value.removeprefix(REPLAY_MARKER)) if parts.scheme: raise ValueError(f"Unexpected scheme in value: {value} {parts.scheme}") @@ -427,9 +451,17 @@ def get_document_uri(self, item_path: ZimPath, item_fragment: str) -> str: URI. """ + # strip the replay marker (if any) before parsing: urlsplit would otherwise + # misparse e.g. "replay://example.com/foo" as having an actual scheme + # ("replay") and hostname ("example.com"). Both item_path and article_path are + # stripped independently and consistently, so the marker (when present on + # both, as it normally is) simply cancels out as a shared leading segment and + # never needs to be reintroduced into the computed relative path. + unmarked_item_value = item_path.value.removeprefix(REPLAY_MARKER) + # a ZIM path is never URL-encoded, so a `#` in it is a literal character # (e.g. coming from a `%23` in original URL) and not a fragment delimiter - item_parts = urlsplit(item_path.value, allow_fragments=False) + item_parts = urlsplit(unmarked_item_value, allow_fragments=False) # item_path is both path + querystring, both will be url-encoded in the document # so that readers consider them as a whole and properly pass them to libzim @@ -438,7 +470,9 @@ def get_document_uri(self, item_path: ZimPath, item_fragment: str) -> str: item_url += "?" + item_parts.query # drop `.` segments of the article path, as PurePosixPath used to do article_path = "/".join( - part for part in self.article_path.value.split("/") if part != "." + part + for part in self.article_path.value.removeprefix(REPLAY_MARKER).split("/") + if part != "." ) article_dir = ( article_path.removesuffix("/") @@ -554,7 +588,7 @@ def normalize(cls, url: HttpUrl) -> ZimPath: to transform some URLs into replay URLs and drop some useless stuff. Returned value is a ZIM path, without any puny/url encoding applied, ready to be - passed to python-libzim for UTF-8 encoding. + passed to python-libzim for UTF-8 encoding, prefixed with `REPLAY_MARKER`. """ url_parts = urlsplit(url.value) @@ -606,4 +640,6 @@ def normalize(cls, url: HttpUrl) -> ZimPath: f"{hostname}{path}{query}" ) - return ZimPath(ArticleUrlRewriter.escape_dot_segments(fuzzified_url)) + return ZimPath( + REPLAY_MARKER + ArticleUrlRewriter.escape_dot_segments(fuzzified_url) + ) diff --git a/tests/rewriting/test_html_rewriting.py b/tests/rewriting/test_html_rewriting.py index 914bcb8b..71df415e 100644 --- a/tests/rewriting/test_html_rewriting.py +++ b/tests/rewriting/test_html_rewriting.py @@ -16,6 +16,7 @@ ) from zimscraperlib.rewriting.js import JsRewriter from zimscraperlib.rewriting.url_rewriting import ( + REPLAY_MARKER, ArticleUrlRewriter, HttpUrl, ZimPath, @@ -353,7 +354,7 @@ def test_rewrite(rewrite_url: ContentForTests): HtmlRewriter( ArticleUrlRewriter( article_url=HttpUrl(f"http://{rewrite_url.article_url}"), - existing_zim_paths={ZimPath("exemple.com/a/long/path")}, + existing_zim_paths={ZimPath(REPLAY_MARKER + "exemple.com/a/long/path")}, ), None, None, @@ -379,7 +380,7 @@ def test_extract_title(): HtmlRewriter( ArticleUrlRewriter( article_url=HttpUrl("http://example.com"), - existing_zim_paths={ZimPath("exemple.com/a/long/path")}, + existing_zim_paths={ZimPath(REPLAY_MARKER + "exemple.com/a/long/path")}, ), None, None, @@ -395,7 +396,7 @@ def test_rewrite_attributes(): rewriter = HtmlRewriter( ArticleUrlRewriter( article_url=HttpUrl("http://kiwix.org/"), - existing_zim_paths={ZimPath("kiwix.org/foo")}, + existing_zim_paths={ZimPath(REPLAY_MARKER + "kiwix.org/foo")}, ), None, None, @@ -542,7 +543,7 @@ def custom_notify(zim_path: ZimPath): ).rewrite(f'') assert len(js_modules) == 1 - assert js_modules[0].value == expected_js_module_path + assert js_modules[0].value == REPLAY_MARKER + expected_js_module_path @pytest.mark.parametrize( @@ -577,7 +578,7 @@ def custom_notify(zim_path: ZimPath): ).rewrite(f'') assert len(js_modules) == 1 - assert js_modules[0].value == expected_js_module_path + assert js_modules[0].value == REPLAY_MARKER + expected_js_module_path @pytest.mark.parametrize( @@ -628,7 +629,10 @@ def custom_notify(zim_path: ZimPath): ) assert len(js_modules) == 1 - assert js_modules[0].value == "kiwix.org/my_other_folder/my-module-script.js" + assert ( + js_modules[0].value + == REPLAY_MARKER + "kiwix.org/my_other_folder/my-module-script.js" + ) def test_js_module_base_href_inline(): @@ -654,7 +658,10 @@ def custom_notify(zim_path: ZimPath): ) assert len(js_modules) == 1 - assert js_modules[0].value == "kiwix.org/my_other_folder/my-module-script.js" + assert ( + js_modules[0].value + == REPLAY_MARKER + "kiwix.org/my_other_folder/my-module-script.js" + ) @pytest.mark.parametrize( @@ -795,11 +802,11 @@ def test_rewrite_base_href(rewrite_base_href_content: ContentForTests): ArticleUrlRewriter( article_url=HttpUrl(f"http://{rewrite_base_href_content.article_url}"), existing_zim_paths={ - ZimPath("kiwix.org/foo.html"), - ZimPath("kiwix.org/foo.js"), - ZimPath("kiwix.org/foo.css"), - ZimPath("kiwix.org/foo.png"), - ZimPath("kiwix.org/favicon.png"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.js"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.css"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.png"), + ZimPath(REPLAY_MARKER + "kiwix.org/favicon.png"), }, ), None, @@ -919,11 +926,11 @@ def test_rewrite_onxxx_event(rewrite_onxxx_content: ContentForTests): ArticleUrlRewriter( article_url=HttpUrl(f"http://{rewrite_onxxx_content.article_url}"), existing_zim_paths={ - ZimPath("kiwix.org/foo.html"), - ZimPath("kiwix.org/foo.js"), - ZimPath("kiwix.org/foo.css"), - ZimPath("kiwix.org/foo.png"), - ZimPath("kiwix.org/favicon.png"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.js"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.css"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.png"), + ZimPath(REPLAY_MARKER + "kiwix.org/favicon.png"), }, ), None, @@ -1016,7 +1023,7 @@ def test_rewrite_meta_http_equiv_redirect_full( article_url=HttpUrl( f"http://{rewrite_meta_http_equiv_redirect_full_content.article_url}" ), - existing_zim_paths={ZimPath("kiwix.org/somepage")}, + existing_zim_paths={ZimPath(REPLAY_MARKER + "kiwix.org/somepage")}, ), None, None, diff --git a/tests/rewriting/test_js_rewriting.py b/tests/rewriting/test_js_rewriting.py index 6a1d3af3..61de3363 100644 --- a/tests/rewriting/test_js_rewriting.py +++ b/tests/rewriting/test_js_rewriting.py @@ -4,6 +4,7 @@ from zimscraperlib.rewriting.js import JsRewriter from zimscraperlib.rewriting.url_rewriting import ( + REPLAY_MARKER, ArticleUrlRewriter, HttpUrl, ZimPath, @@ -651,7 +652,7 @@ def custom_notify(zim_path: ZimPath): ).rewrite(f'import * from "{js_src}"', opts={"isModule": True}) assert len(js_modules) == 1 - assert js_modules[0].value == expected_js_module_path + assert js_modules[0].value == REPLAY_MARKER + expected_js_module_path # Marker string present in the test fixtures below, matching the one real diff --git a/tests/rewriting/test_url_rewriting.py b/tests/rewriting/test_url_rewriting.py index 926a6666..15aefbbb 100644 --- a/tests/rewriting/test_url_rewriting.py +++ b/tests/rewriting/test_url_rewriting.py @@ -3,6 +3,7 @@ import pytest from zimscraperlib.rewriting.url_rewriting import ( + REPLAY_MARKER, ArticleUrlRewriter, HttpUrl, RewriteResult, @@ -161,7 +162,8 @@ class TestNormalize: ) def test_normalize(self, url: str, zim_path: str): assert ( - ArticleUrlRewriter.normalize(HttpUrl(url)).value == ZimPath(zim_path).value + ArticleUrlRewriter.normalize(HttpUrl(url)).value + == ZimPath(REPLAY_MARKER + zim_path).value ) @@ -212,7 +214,7 @@ class TestArticleUrlRewriter: ), ( "bar.html", - {ZimPath("kiwix.org/a/article/bar.html")}, + {ZimPath(REPLAY_MARKER + "kiwix.org/a/article/bar.html")}, ), ], ) @@ -225,7 +227,9 @@ def test_missing_zim_paths( missing_zim_paths: set[ZimPath] = set() rewriter = ArticleUrlRewriter( article_url=http_article_url, - existing_zim_paths={ZimPath("kiwix.org/a/article/foo.html")}, + existing_zim_paths={ + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html") + }, missing_zim_paths=missing_zim_paths, ) rewriter(original_content_url, base_href=None, rewrite_all_url=False) @@ -241,7 +245,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html", "foo.html", - ZimPath("kiwix.org/a/article/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), ), ["kiwix.org/a/article/foo.html"], False, @@ -252,7 +256,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html#anchor1", "foo.html#anchor1", - ZimPath("kiwix.org/a/article/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), ), ["kiwix.org/a/article/foo.html"], False, @@ -263,7 +267,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html?foo=bar", "foo.html%3Ffoo=bar", - ZimPath("kiwix.org/a/article/foo.html?foo=bar"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html?foo=bar"), ), ["kiwix.org/a/article/foo.html?foo=bar"], False, @@ -274,7 +278,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html?foo=b%24ar", "foo.html%3Ffoo=b%24ar", - ZimPath("kiwix.org/a/article/foo.html?foo=b$ar"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html?foo=b$ar"), ), ["kiwix.org/a/article/foo.html?foo=b$ar"], False, @@ -285,7 +289,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html?foo=b%3Far", "foo.html%3Ffoo=b%3Far", - ZimPath("kiwix.org/a/article/foo.html?foo=b?ar"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html?foo=b?ar"), ), ["kiwix.org/a/article/foo.html?foo=b?ar"], False, @@ -296,7 +300,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo%23bar.html", "foo%23bar.html", - ZimPath("kiwix.org/a/article/foo#bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo#bar.html"), ), ["kiwix.org/a/article/foo#bar.html"], False, @@ -307,7 +311,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo%23bar.html#anchor1", "foo%23bar.html#anchor1", - ZimPath("kiwix.org/a/article/foo#bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo#bar.html"), ), ["kiwix.org/a/article/foo#bar.html"], False, @@ -318,7 +322,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html?foo=b%23ar", "foo.html%3Ffoo=b%23ar", - ZimPath("kiwix.org/a/article/foo.html?foo=b#ar"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html?foo=b#ar"), ), ["kiwix.org/a/article/foo.html?foo=b#ar"], False, @@ -329,7 +333,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/fo%o.html", "fo%25o.html", - ZimPath("kiwix.org/a/article/fo%o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/fo%o.html"), ), ["kiwix.org/a/article/fo%o.html"], False, @@ -341,7 +345,7 @@ def test_missing_zim_paths( "https://kiwix.org/a/article/foé.html", "fo%C3%A9.html", # character is encoded so that URL match RFC 3986 ZimPath( - "kiwix.org/a/article/foé.html" + REPLAY_MARKER + "kiwix.org/a/article/foé.html" ), # but ZIM path is non-encoded ), ["kiwix.org/a/article/foé.html"], @@ -353,7 +357,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo.html", "foo.html", - ZimPath("kiwix.org/a/article/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), ), ["kiwix.org/a/article/foo.html"], False, @@ -364,7 +368,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/foo.html", "https://kiwix.org/a/foo.html", # Full URL since not in known URLs - ZimPath("kiwix.org/a/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/foo.html"), ), ["kiwix.org/a/article/foo.html"], False, @@ -375,7 +379,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/foo.html", "../foo.html", # all URLs rewrite activated - ZimPath("kiwix.org/a/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/foo.html"), ), ["kiwix.org/a/article/foo.html"], True, @@ -386,7 +390,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/foo.html", "../foo.html", - ZimPath("kiwix.org/a/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/foo.html"), ), ["kiwix.org/a/foo.html"], False, @@ -398,7 +402,7 @@ def test_missing_zim_paths( "https://kiwix.org/a/bar/foo.html", "https://kiwix.org/a/bar/foo.html", # Full URL since not in known # URLs - ZimPath("kiwix.org/a/bar/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/bar/foo.html"), ), ["kiwix.org/a/article/foo.html"], False, @@ -409,7 +413,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/bar/foo.html", "../bar/foo.html", # all URLs rewrite activated - ZimPath("kiwix.org/a/bar/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/bar/foo.html"), ), ["kiwix.org/a/article/foo.html"], True, @@ -420,7 +424,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/bar/foo.html", "../bar/foo.html", - ZimPath("kiwix.org/a/bar/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/bar/foo.html"), ), ["kiwix.org/a/bar/foo.html"], False, @@ -431,7 +435,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/foo.html", "../../foo.html", - ZimPath("kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), ), ["kiwix.org/foo.html"], False, @@ -442,7 +446,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo?param=value", "foo%3Fparam=value", - ZimPath("kiwix.org/a/article/foo?param=value"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo?param=value"), ), ["kiwix.org/a/article/foo?param=value"], False, @@ -453,7 +457,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo?param=value%2F", "foo%3Fparam=value/", - ZimPath("kiwix.org/a/article/foo?param=value/"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo?param=value/"), ), ["kiwix.org/a/article/foo?param=value/"], False, @@ -464,7 +468,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo?param=value%2Fend", "foo%3Fparam=value/end", - ZimPath("kiwix.org/a/article/foo?param=value/end"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo?param=value/end"), ), ["kiwix.org/a/article/foo?param=value/end"], False, @@ -478,7 +482,10 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo?k=ytembeds.base.en_US,foo.bar", "foo%3Fk=ytembeds.base.en_US,foo.bar", - ZimPath("kiwix.org/a/article/foo?k=ytembeds.base.en_US,foo.bar"), + ZimPath( + REPLAY_MARKER + + "kiwix.org/a/article/foo?k=ytembeds.base.en_US,foo.bar" + ), ), ["kiwix.org/a/article/foo?k=ytembeds.base.en_US,foo.bar"], False, @@ -489,7 +496,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/foo/", "foo/", - ZimPath("kiwix.org/a/article/foo/"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo/"), ), ["kiwix.org/a/article/foo/"], False, @@ -500,7 +507,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo o.html", "../../fo%20o.html", - ZimPath("kiwix.org/fo o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo o.html"), ), ["kiwix.org/fo o.html"], False, @@ -511,7 +518,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo+o.html", "../../fo%2Bo.html", - ZimPath("kiwix.org/fo+o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo+o.html"), ), ["kiwix.org/fo+o.html"], False, @@ -522,7 +529,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo%2Bo.html", "../../fo%2Bo.html", - ZimPath("kiwix.org/fo+o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo+o.html"), ), ["kiwix.org/fo+o.html"], False, @@ -533,7 +540,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/foo.html?param=val+ue", "../../foo.html%3Fparam=val%20ue", - ZimPath("kiwix.org/foo.html?param=val ue"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html?param=val ue"), ), ["kiwix.org/foo.html?param=val ue"], False, @@ -544,7 +551,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo~o.html", "../../fo~o.html", - ZimPath("kiwix.org/fo~o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo~o.html"), ), ["kiwix.org/fo~o.html"], False, @@ -555,7 +562,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo-o.html", "../../fo-o.html", - ZimPath("kiwix.org/fo-o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo-o.html"), ), ["kiwix.org/fo-o.html"], False, @@ -566,7 +573,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo_o.html", "../../fo_o.html", - ZimPath("kiwix.org/fo_o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo_o.html"), ), ["kiwix.org/fo_o.html"], False, @@ -577,7 +584,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo%7Eo.html", "../../fo~o.html", - ZimPath("kiwix.org/fo~o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo~o.html"), ), ["kiwix.org/fo~o.html"], False, @@ -588,7 +595,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo%2Do.html", "../../fo-o.html", - ZimPath("kiwix.org/fo-o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo-o.html"), ), ["kiwix.org/fo-o.html"], False, @@ -599,7 +606,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/fo%5Fo.html", "../../fo_o.html", - ZimPath("kiwix.org/fo_o.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/fo_o.html"), ), ["kiwix.org/fo_o.html"], False, @@ -610,7 +617,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/foo%2Ehtml", "../../foo.html", - ZimPath("kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), ), ["kiwix.org/foo.html"], False, @@ -643,7 +650,7 @@ def test_missing_zim_paths( RewriteResult( "https://kiwix.org/a/article/", "./", - ZimPath("kiwix.org/a/article/"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/"), ), ["kiwix.org/a/article/"], False, @@ -662,7 +669,7 @@ def test_relative_url( http_article_url = HttpUrl(article_url) rewriter = ArticleUrlRewriter( article_url=http_article_url, - existing_zim_paths={ZimPath(path) for path in know_paths}, + existing_zim_paths={ZimPath(REPLAY_MARKER + path) for path in know_paths}, ) assert ( rewriter( @@ -680,7 +687,7 @@ def test_relative_url( RewriteResult( "https://example.com/a///b", "a///b", - ZimPath("example.com/a///b"), + ZimPath(REPLAY_MARKER + "example.com/a///b"), ), ), ( @@ -689,7 +696,7 @@ def test_relative_url( RewriteResult( "https://example.com/p?q=x//y", "p%3Fq=x//y", - ZimPath("example.com/p?q=x//y"), + ZimPath(REPLAY_MARKER + "example.com/p?q=x//y"), ), ), ( @@ -698,7 +705,7 @@ def test_relative_url( RewriteResult( "https://example.com/a//b/", "a//b/", - ZimPath("example.com/a//b/"), + ZimPath(REPLAY_MARKER + "example.com/a//b/"), ), ), ( @@ -707,7 +714,7 @@ def test_relative_url( RewriteResult( "https://example.com/x//y/other.html", "other.html", - ZimPath("example.com/x//y/other.html"), + ZimPath(REPLAY_MARKER + "example.com/x//y/other.html"), ), ), ( @@ -716,7 +723,7 @@ def test_relative_url( RewriteResult( "https://example.com/x//z.html", "../z.html", - ZimPath("example.com/x//z.html"), + ZimPath(REPLAY_MARKER + "example.com/x//z.html"), ), ), ( @@ -725,7 +732,7 @@ def test_relative_url( RewriteResult( "https://example.com/a.html", "../../../a.html", - ZimPath("example.com/a.html"), + ZimPath(REPLAY_MARKER + "example.com/a.html"), ), ), ( @@ -734,7 +741,7 @@ def test_relative_url( RewriteResult( "https://example.com/x//y/other.html", "other.html", - ZimPath("example.com/x//y/other.html"), + ZimPath(REPLAY_MARKER + "example.com/x//y/other.html"), ), ), ( @@ -743,7 +750,7 @@ def test_relative_url( RewriteResult( "https://example.com/x//z.html", "../z.html", - ZimPath("example.com/x//z.html"), + ZimPath(REPLAY_MARKER + "example.com/x//z.html"), ), ), ], @@ -771,7 +778,7 @@ def test_relative_url_query_only_reference(self): ) == RewriteResult( "https://example.com/index.html?page=2", "index.html%3Fpage=2", - ZimPath("example.com/index.html?page=2"), + ZimPath(REPLAY_MARKER + "example.com/index.html?page=2"), ) @pytest.mark.parametrize( @@ -839,7 +846,7 @@ def test_relative_url_round_trip( RewriteResult( "https://kiwix.org/foo.html", "../../foo.html", - ZimPath("kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), ), ["kiwix.org/foo.html"], False, @@ -850,7 +857,7 @@ def test_relative_url_round_trip( RewriteResult( "https://kiwix.org/bar.html", "https://kiwix.org/bar.html", # Full URL since not in known URLs - ZimPath("kiwix.org/bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/bar.html"), ), ["kiwix.org/foo.html"], False, @@ -861,7 +868,7 @@ def test_relative_url_round_trip( RewriteResult( "https://kiwix.org/bar.html", "../../bar.html", # all URLs rewrite activated - ZimPath("kiwix.org/bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/bar.html"), ), ["kiwix.org/foo.html"], True, @@ -880,7 +887,7 @@ def test_absolute_path_url( http_article_url = HttpUrl(article_url) rewriter = ArticleUrlRewriter( article_url=http_article_url, - existing_zim_paths={ZimPath(path) for path in know_paths}, + existing_zim_paths={ZimPath(REPLAY_MARKER + path) for path in know_paths}, ) assert ( rewriter( @@ -899,7 +906,7 @@ def test_absolute_path_url( RewriteResult( "https://kiwix.org/foo.html", "../../foo.html", - ZimPath("kiwix.org/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/foo.html"), ), ["kiwix.org/foo.html"], False, @@ -910,7 +917,7 @@ def test_absolute_path_url( RewriteResult( "https://kiwix.org/bar.html", "https://kiwix.org/bar.html", # Full URL since not in known URLs - ZimPath("kiwix.org/bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/bar.html"), ), ["kiwix.org/foo.html"], False, @@ -921,7 +928,7 @@ def test_absolute_path_url( RewriteResult( "https://kiwix.org/bar.html", "../../bar.html", # all URLs rewrite activated - ZimPath("kiwix.org/bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/bar.html"), ), ["kiwix.org/foo.html"], True, @@ -932,7 +939,7 @@ def test_absolute_path_url( RewriteResult( "https://acme.com/foo.html", "../../../acme.com/foo.html", - ZimPath("acme.com/foo.html"), + ZimPath(REPLAY_MARKER + "acme.com/foo.html"), ), ["acme.com/foo.html"], False, @@ -943,7 +950,7 @@ def test_absolute_path_url( RewriteResult( "http://acme.com/bar.html", "http://acme.com/bar.html", # Full URL since not in known URLs - ZimPath("acme.com/bar.html"), + ZimPath(REPLAY_MARKER + "acme.com/bar.html"), ), ["kiwix.org/foo.html"], False, @@ -954,7 +961,7 @@ def test_absolute_path_url( RewriteResult( "https://acme.com/bar.html", "../../../acme.com/bar.html", # all URLs rewrite activated - ZimPath("acme.com/bar.html"), + ZimPath(REPLAY_MARKER + "acme.com/bar.html"), ), ["kiwix.org/foo.html"], True, @@ -965,7 +972,7 @@ def test_absolute_path_url( RewriteResult( "https://xn--exmple-cva.com/a/article/document.html", "../../../ex%C3%A9mple.com/a/article/document.html", - ZimPath("exémple.com/a/article/document.html"), + ZimPath(REPLAY_MARKER + "exémple.com/a/article/document.html"), ), ["exémple.com/a/article/document.html"], False, @@ -976,7 +983,7 @@ def test_absolute_path_url( RewriteResult( "https://exémple.com/a/article/document.html", "../../../ex%C3%A9mple.com/a/article/document.html", - ZimPath("exémple.com/a/article/document.html"), + ZimPath(REPLAY_MARKER + "exémple.com/a/article/document.html"), ), ["exémple.com/a/article/document.html"], False, @@ -995,7 +1002,7 @@ def test_absolute_scheme_url( http_article_url = HttpUrl(article_url) rewriter = ArticleUrlRewriter( article_url=http_article_url, - existing_zim_paths={ZimPath(path) for path in know_paths}, + existing_zim_paths={ZimPath(REPLAY_MARKER + path) for path in know_paths}, ) assert ( rewriter( @@ -1014,7 +1021,7 @@ def test_absolute_scheme_url( RewriteResult( "https://foo.org/a/article/document.html", "../../../foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["foo.org/a/article/document.html"], False, @@ -1026,7 +1033,7 @@ def test_absolute_scheme_url( RewriteResult( "http://foo.org/a/article/document.html", "../../../foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["foo.org/a/article/document.html"], False, @@ -1038,7 +1045,7 @@ def test_absolute_scheme_url( RewriteResult( "https://foo.org/a/article/document.html", "../../../foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["foo.org/a/article/document.html"], False, @@ -1050,7 +1057,7 @@ def test_absolute_scheme_url( RewriteResult( "https://user:password@foo.org:8080/a/article/document.html", "../../../foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["foo.org/a/article/document.html"], False, @@ -1062,7 +1069,7 @@ def test_absolute_scheme_url( RewriteResult( "https://foo.org/a/article/document.html", "https://foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["kiwix.org/a/article/foo/"], False, @@ -1074,7 +1081,7 @@ def test_absolute_scheme_url( RewriteResult( "https://foo.org/a/article/document.html", "../../../foo.org/a/article/document.html", - ZimPath("foo.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "foo.org/a/article/document.html"), ), ["kiwix.org/a/article/foo/"], True, @@ -1086,7 +1093,7 @@ def test_absolute_scheme_url( RewriteResult( "https://xn--exmple-cva.com/a/article/document.html", "../../../ex%C3%A9mple.com/a/article/document.html", - ZimPath("exémple.com/a/article/document.html"), + ZimPath(REPLAY_MARKER + "exémple.com/a/article/document.html"), ), ["exémple.com/a/article/document.html"], False, @@ -1099,7 +1106,7 @@ def test_absolute_scheme_url( RewriteResult( "https://exémple.com/a/article/document.html", "../../../ex%C3%A9mple.com/a/article/document.html", - ZimPath("exémple.com/a/article/document.html"), + ZimPath(REPLAY_MARKER + "exémple.com/a/article/document.html"), ), ["exémple.com/a/article/document.html"], False, @@ -1119,7 +1126,7 @@ def test_absolute_url( http_article_url = HttpUrl(article_url) rewriter = ArticleUrlRewriter( article_url=http_article_url, - existing_zim_paths={ZimPath(path) for path in know_paths}, + existing_zim_paths={ZimPath(REPLAY_MARKER + path) for path in know_paths}, ) assert ( rewriter( @@ -1161,7 +1168,7 @@ def test_no_rewrite_other_schemes( RewriteResult( "https://kiwix.org/a/article/foo.html", "foo.html", - ZimPath("kiwix.org/a/article/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), ), id="no_base", ), @@ -1172,7 +1179,7 @@ def test_no_rewrite_other_schemes( RewriteResult( "https://kiwix.org/a/foo.html", "../foo.html", - ZimPath("kiwix.org/a/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/foo.html"), ), id="parent_base", ), @@ -1183,7 +1190,7 @@ def test_no_rewrite_other_schemes( RewriteResult( "https://kiwix.org/a/bar/foo.html", "../bar/foo.html", - ZimPath("kiwix.org/a/bar/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/bar/foo.html"), ), id="base_in_another_folder", ), @@ -1194,7 +1201,7 @@ def test_no_rewrite_other_schemes( RewriteResult( "https://www.example.com/foo.html", "../../../www.example.com/foo.html", - ZimPath("www.example.com/foo.html"), + ZimPath(REPLAY_MARKER + "www.example.com/foo.html"), ), id="base_on_absolute_url", ), @@ -1205,7 +1212,7 @@ def test_no_rewrite_other_schemes( RewriteResult( "https://kiwix.org/a/a//bar/foo.html", "../a//bar/foo.html", - ZimPath("kiwix.org/a/a//bar/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/a//bar/foo.html"), ), id="base_with_consecutive_slashes", ), @@ -1220,13 +1227,54 @@ def test_base_href( ): rewriter = ArticleUrlRewriter( article_url=HttpUrl("https://kiwix.org/a/article/document.html"), - existing_zim_paths={ZimPath(know_path)}, + existing_zim_paths={ZimPath(REPLAY_MARKER + know_path)}, ) assert ( rewriter(original_content_url, base_href=base_href, rewrite_all_url=False) == expected_rewriten_result ) + @pytest.mark.parametrize( + "article_path, item_path, expected_uri", + [ + # both marked (the normal case, as produced by normalize()): the marker is + # stripped from both sides before computing the relative path, so it is a + # shared leading segment and never appears in the computed href + ( + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/document.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), + "foo.html", + ), + # article_path unmarked (e.g. a static asset path built directly, like + # `_zim_static/__wb_module_decl.js`), item_path marked: the marker is + # still stripped from item_path, so it never leaks into the output, but + # there is no shared prefix left to cancel out against the (always + # unmarked) `_zim_static/` article_path, same as before REPLAY_MARKER + # existed + ( + ZimPath("_zim_static/"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), + "../kiwix.org/a/article/foo.html", + ), + # the reverse: article_path marked, item_path unmarked; same result as + # today since the marker is only ever a shared prefix when both sides + # have it + ( + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/document.html"), + ZimPath("_zim_static/wombat.js"), + "../../../_zim_static/wombat.js", + ), + ], + ) + def test_get_document_uri_marker_mismatch( + self, article_path: ZimPath, item_path: ZimPath, expected_uri: str + ): + rewriter = ArticleUrlRewriter( + article_url=HttpUrl("https://kiwix.org/a/article/document.html"), + article_path=article_path, + ) + assert rewriter.get_document_uri(item_path, "") == expected_uri + class CustomRewriter(ArticleUrlRewriter): """Sample class using the rewriting result to process items to download @@ -1271,8 +1319,8 @@ def test_items_to_download(self): rewriter = CustomRewriter( article_url=HttpUrl("https://kiwix.org/a/article/document.html"), existing_zim_paths={ - ZimPath("kiwix.org/a/article/foo.html"), - ZimPath("kiwix.org/a/article/bar.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/bar.html"), }, ) rewriter("foo.html#anchor1", base_href=None, rewrite_all_url=False) @@ -1280,11 +1328,11 @@ def test_items_to_download(self): rewriter("bar.html", base_href=None, rewrite_all_url=False) rewriter("missing.html", base_href=None, rewrite_all_url=False) assert rewriter.items_to_download == { - ZimPath("kiwix.org/a/article/foo.html"): { + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"): { HttpUrl("https://kiwix.org/a/article/foo.html#anchor1"), HttpUrl("https://kiwix.org/a/article/foo.html#anchor2"), }, - ZimPath("kiwix.org/a/article/bar.html"): { + ZimPath(REPLAY_MARKER + "kiwix.org/a/article/bar.html"): { HttpUrl("https://kiwix.org/a/article/bar.html") }, } @@ -1336,6 +1384,10 @@ class TestZimPath: [ ("content/index.html"), ("index.html"), + # a value prefixed with REPLAY_MARKER (as produced by `normalize`) is + # just as valid as an unmarked one + (REPLAY_MARKER + "content/index.html"), + (REPLAY_MARKER + "index.html"), ], ) def test_good_zim_path(self, path: str): @@ -1349,6 +1401,8 @@ def test_good_zim_path(self, path: str): ("mailto:bob@acme.com"), ("tel:+41.34.34"), ("mailto:https://bob@acme.com"), + # the REPLAY_MARKER prefix doesn't hide a genuinely bad scheme behind it + (REPLAY_MARKER + "https://bob@acme.com"), ], ) def test_bad_zim_path_scheme(self, path: str): @@ -1429,8 +1483,9 @@ def _resolve_relative_reference(base_url: str, reference: str) -> str: """Resolve a relative-path reference as browsers do (RFC 3986 section 5.2) Unlike `urllib.parse.urljoin`, empty path segments are kept. Returns the host - and path of the resolved URL, i.e. the form of a ZIM path. + and path of the resolved URL, i.e. the form of a ZIM path (including its + `REPLAY_MARKER` prefix). """ base = urlsplit(base_url) merged_path = base.path.rpartition("/")[0] + "/" + reference.partition("#")[0] - return f"{base.netloc}{_remove_dot_segments(merged_path)}" + return f"{REPLAY_MARKER}{base.netloc}{_remove_dot_segments(merged_path)}" From afbbb180e7239b787db0f1d75ea0ee7e3262d3e4 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Tue, 17 Nov 2026 13:19:53 +0000 Subject: [PATCH 2/2] Shorten REPLAY_MARKER from "replay://" to "-/" and anchor isAlreadyPrefixed to prefix Found through end-to-end testing: kiwix-serve (like some other servers) percent-encodes ":" in a redirect's Location header, turning "replay://" into "replay%3A//" on the one path reached via a redirect (the ZIM's main page). Browsers don't decode %3A back when exposing location.href, so wombat.js would end up computing wb_rel_prefix with the escaped form while every freshly-rewritten href on the page still uses the unescaped one, making wb_unrewrite_rx fail to match (and hence fail to strip) wombat's own rewrite prefix specifically on that page - a quieter, inverted sibling of the original degenerate-regex bug, caused by an entirely different mechanism (server-side escaping rather than an empty prefix). "-/" has no character any URL-handling code has reason to percent-encode, closing that whole bug class rather than papering over this one instance of it. It also removes the need for: - stripping the marker before urlsplit (its "-" isn't a valid scheme start character, so urlsplit never mistakes anything after it for a scheme/netloc, unlike "replay://" which required explicit stripping in ZimPath.check_validity and get_document_uri) - restoring "%3A" after encodeURIComponent in urlRewriteFunction A bare "-" (no trailing slash) was considered and rejected: wombat's unrewrite regex is `wb_rel_prefix + '[^/]+/'`, and without the "/" the result degenerates to "/-[^/]+/", which is common enough in ordinary text (negative indices like "/-1/", CSS vendor prefixes like "/-webkit-x/") to misfire the same way the original bug did, just on a narrower set of inputs. Confirmed by testing realistic samples against the actual regex before deciding. isAlreadyPrefixed(url) is now isAlreadyPrefixed(url, prefix), checking `url.startsWith(prefix + REPLAY_MARKER)` instead of a bare `url.includes(REPLAY_MARKER)`. This was already desirable with the old marker (a scheme-shaped string is a poor fit for a loose substring check) but becomes necessary with the shorter one: "-/" alone is a plausible real path segment (e.g. a video/sports "replay" section), so anchoring the check to our own serving prefix - unique to this deployment, impossible for genuine external content to coincidentally match - is what actually keeps the false-positive risk at zero regardless of marker length. --- javascript/src/wombatSetup.js | 30 +++-- javascript/test/wombatUrlRewriting.js | 120 +++++++++---------- src/zimscraperlib/rewriting/url_rewriting.py | 53 ++++---- tests/rewriting/test_js_rewriting.py | 11 +- tests/rewriting/test_url_rewriting.py | 33 ++--- 5 files changed, 133 insertions(+), 114 deletions(-) diff --git a/javascript/src/wombatSetup.js b/javascript/src/wombatSetup.js index ad932bc8..f7457320 100644 --- a/javascript/src/wombatSetup.js +++ b/javascript/src/wombatSetup.js @@ -221,7 +221,14 @@ if (typeof crypto !== 'undefined' && typeof crypto.subtle === 'undefined') { // "collection" path segment (e.g. bare `kiwix.app/`) made wombat.js's // `wb_rel_prefix` degenerate to `''`/`'/'`, corrupting any `innerHTML`/`outerHTML` // read on the page (webrecorder/wombat, reported as openzim/zimit#589). -export const REPLAY_MARKER = 'replay://'; +// `-` was chosen because it is never percent-encoded by `encodeURIComponent` +// (unlike e.g. `:`, which some servers percent-encode in a redirect's `Location` +// header, defeating the marker's purpose) and a hostname can never start with +// one, but a bare `-` alone would not be enough: wombat's regex is +// `wb_rel_prefix + '[^/]+/'`, and without the trailing `/` the resulting +// `/-[^/]+/` is still common enough in ordinary text (e.g. `/-1/`, `/-webkit-x/`) +// to misfire the same way. +export const REPLAY_MARKER = '-/'; export function applyFuzzyRules(path) { // Apply fuzzy rules to simplify the ZIM path. First matching rule is applied and @@ -250,17 +257,19 @@ export function escapeDotSegments(path) { .join('/'); } -export function isAlreadyPrefixed(url) { - // REPLAY_MARKER is a constant marker we prepend to every ZIM path (see - // urlRewriteFunction below), so any URL containing it is unambiguously an +export function isAlreadyPrefixed(url, prefix) { + // Checking for REPLAY_MARKER right after our own serving prefix (rather than + // anywhere in url) anchors the check to something unique to this deployment, + // so it cannot coincidentally match genuine, unrelated content that happens to + // contain REPLAY_MARKER as a substring (e.g. a real site with a URL segment + // literally named "replay"). Any url shaped this way is unambiguously an // already-rewritten, fully-prefixed absolute URL (e.g. one read back from - // `img.src` and reassigned elsewhere): original web content cannot - // coincidentally produce it. A statically-rewritten *relative* link never - // contains it, since the marker is a shared prefix between the current + // `img.src` and reassigned elsewhere). A statically-rewritten *relative* link + // never matches here, since the marker is a shared prefix between the current // document and the link's target, and so is absent from the relative // reference computed between them (see `hasAlreadyBeenRewritten` for that // case instead). - return url.includes(REPLAY_MARKER); + return url.startsWith(prefix + REPLAY_MARKER); } export function hasAlreadyBeenRewritten( @@ -329,7 +338,7 @@ export function urlRewriteFunction( // in particular, the prefix-unwrapping a few lines down would otherwise mangle // such a URL (e.g. one read back from `img.src` and reassigned elsewhere) by // re-adding a scheme in front of its embedded REPLAY_MARKER. - if (isAlreadyPrefixed(url)) { + if (isAlreadyPrefixed(url, prefix)) { return url; } @@ -422,8 +431,7 @@ export function urlRewriteFunction( encodeURIComponent(REPLAY_MARKER + escapedPath) .replaceAll('%2F', '/') .replaceAll('%3D', '=') - .replaceAll('%2C', ',') - .replaceAll('%3A', ':'); + .replaceAll('%2C', ','); console.debug( 'urlRewriten:\n\t- current_url: ' + diff --git a/javascript/test/wombatUrlRewriting.js b/javascript/test/wombatUrlRewriting.js index 5e89b489..26df16ac 100644 --- a/javascript/test/wombatUrlRewriting.js +++ b/javascript/test/wombatUrlRewriting.js @@ -46,7 +46,7 @@ test('simpleContentCompleteUrl', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -63,7 +63,7 @@ test('simpleContentFullUrl', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -80,7 +80,7 @@ test('simpleContentNoScheme', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -97,7 +97,7 @@ test('consecutiveSlashesAreKept', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/a///b', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/a///b', ); }); @@ -120,7 +120,7 @@ test('relativeLinkOnPageWithConsecutiveSlashesKeepsThem', (t) => { undefined, undefined, ), - t.context.prefix + 'replay://www.example.com/path1//other.html', + t.context.prefix + '-/www.example.com/path1//other.html', ); }); @@ -137,7 +137,7 @@ test('simpleContentEmptyPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/', ); }); @@ -154,7 +154,7 @@ test('simpleContentNoPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/', ); }); @@ -171,7 +171,7 @@ test('contentWithSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -188,7 +188,7 @@ test('contentWithUTF8CharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%F0%9F%8E%81nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%F0%9F%8E%81nt.txt', ); }); @@ -205,7 +205,7 @@ test('contentWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -222,7 +222,7 @@ test('contentWithSpaceNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%20nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%20nt.txt', ); }); @@ -239,7 +239,7 @@ test('contentWithPlusNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%2Bnt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%2Bnt.txt', ); }); @@ -256,7 +256,7 @@ test('contentWithTilde', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont~nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont~nt.txt', ); }); @@ -273,7 +273,7 @@ test('contentWithHyphen', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont-nt.txt', ); }); @@ -290,7 +290,7 @@ test('contentWithUnderscore', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont_nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont_nt.txt', ); }); @@ -307,7 +307,7 @@ test('contentWithEncodedTilde', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont~nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont~nt.txt', ); }); @@ -324,7 +324,7 @@ test('contentWithEncodedApostrophe', (t) => { undefined, undefined, ), - "http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont'nt.txt", + "http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont'nt.txt", ); }); @@ -341,7 +341,7 @@ test('contentWithEncodedExclamationMark', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont!nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont!nt.txt', ); }); @@ -358,7 +358,7 @@ test('contentWithEncodedQuestionMark', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%3Fnt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%3Fnt.txt', ); }); @@ -375,7 +375,7 @@ test('contentWithEncodedQuestionMarkAndQueryParam', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%3Fnt.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%3Fnt.txt%3Fquery=value', ); }); @@ -392,7 +392,7 @@ test('contentWithEncodedStar', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont*nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont*nt.txt', ); }); @@ -409,7 +409,7 @@ test('contentWithEncodedParentheses', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont()nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont()nt.txt', ); }); @@ -426,7 +426,7 @@ test('contentWithEncodedHyphen1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont-nt.txt', ); }); @@ -443,7 +443,7 @@ test('contentWithEncodedHyphen2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/co%25nt-nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/co%25nt-nt.txt', ); }); @@ -460,7 +460,7 @@ test('contentWithEncodedUnderscore', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont_nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont_nt.txt', ); }); @@ -477,7 +477,7 @@ test('contentWithEncodedPeriod', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -494,7 +494,7 @@ test('contentWithSimpleQueryString', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=value', ); }); @@ -513,7 +513,7 @@ test('contentWithQueryStringDotDotSegment', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fcss=../_../prg', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fcss=../_../prg', ); }); @@ -531,7 +531,7 @@ test('contentWithQueryValueRawPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%20ue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=val%20ue', ); }); @@ -553,7 +553,7 @@ test('contentWithQueryValueEncodedPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%2Bue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=val%2Bue', ); }); @@ -570,7 +570,7 @@ test('contentWithSimplePathWithEqualAndComma', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt/query1=value1,param2=value2', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt/query1=value1,param2=value2', ); }); @@ -587,7 +587,7 @@ test('contentWithQueryValueEqualSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val=eue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=val=eue', ); }); @@ -604,7 +604,7 @@ test('contentWithQueryValuePercentSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=val%25eue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=val%25eue', ); }); @@ -621,7 +621,7 @@ test('contentWithQueryParamPercentSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fque%25ry=valeue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fque%25ry=valeue', ); }); @@ -638,7 +638,7 @@ test('contentWithQueryParamPlusSign', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fparam=val%20ue', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fparam=val%20ue', ); }); @@ -655,7 +655,7 @@ test('fqdnWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.%C3%A9xample.com/javascript/content.txt', ); }); @@ -672,7 +672,7 @@ test('fqdnWithSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.%C3%A9xample.com/javascript/content.txt', ); }); @@ -689,7 +689,7 @@ test('fqdnWithSpecialCharsEncodedContentWithSpecialCharsEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.%C3%A9xample.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.%C3%A9xample.com/javascript/cont%C3%A9nt.txt', ); }); @@ -706,7 +706,7 @@ test('relSimpleContent1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -723,7 +723,7 @@ test('relSimpleContent2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/path1/javascript/content.txt', ); }); @@ -740,7 +740,7 @@ test('relGoingUperThanHost', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -757,7 +757,7 @@ test('relSimpleContent3', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -927,7 +927,7 @@ test('youtubeFuzzyNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=123ah', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=123ah', ); }); @@ -944,14 +944,14 @@ test('youtubeFuzzyEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=12=3ah', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/path1/youtube.fuzzy.replayweb.page/get_video_info%3Fvideo_id=12=3ah', ); }); // this specifically exercises isAlreadyPrefixed: without it, the prefix-unwrapping // a few lines into urlRewriteFunction would mangle this fully-prefixed, already // REPLAY_MARKER-containing absolute URL by re-adding a scheme in front of the -// marker (producing e.g. 'http://replay://www.example.com/...'), instead of +// marker (producing e.g. 'http://-/www.example.com/...'), instead of // recognizing it as already rewritten and returning it untouched test('alreadyRewritenUrlSimple', (t) => { t.is( @@ -961,12 +961,12 @@ test('alreadyRewritenUrlSimple', (t) => { t.context.originalScheme, t.context.originalUrl, t.context.prefix, - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', undefined, undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -983,7 +983,7 @@ test('alreadyRewritenUrlSpecialCharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%C3%A9nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%C3%A9nt.txt', ); }); @@ -1000,7 +1000,7 @@ test('alreadyRewritenUrlUTF8CharsNotEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/cont%F0%9F%8E%81nt.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/cont%F0%9F%8E%81nt.txt', ); }); @@ -1017,7 +1017,7 @@ test('simpleContentDomainNameInPath1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/www.example.com/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/www.example.com/content.txt', ); }); @@ -1034,7 +1034,7 @@ test('simpleContentDomainNameInPath2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/www.example.com', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/www.example.com', ); }); @@ -1052,7 +1052,7 @@ test('relAlreadyEncoded', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt%3Fquery=value', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt%3Fquery=value', ); }); @@ -1157,7 +1157,7 @@ test('relTooUpNotLookingLikeAHostname', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -1181,7 +1181,7 @@ test('relTooUpNotLookingLikeAHostnameRootPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -1205,7 +1205,7 @@ test('relTooUpNotLookingLikeAHostnameEmptyPath', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/javascript/content.txt', ); }); @@ -1225,7 +1225,7 @@ test('relNotReallyAnotherHostAlreadyRewrittenTooUp', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/anotherhost.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/anotherhost.com/javascript/content.txt', ); }); @@ -1246,7 +1246,7 @@ test('relNotReallyAnotherHostAlreadyRewrittenNotUpEnough', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://www.example.com/anotherhost.com/javascript/content.txt', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/www.example.com/anotherhost.com/javascript/content.txt', ); }); @@ -1263,7 +1263,7 @@ test('doubleSlash1', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/some/path/http://example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/example.com/some/path/http%3A//example.com//some/path', ); }); @@ -1280,7 +1280,7 @@ test('doubleSlash2', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/some/pa%3Fth/http://example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/example.com/some/pa%3Fth/http%3A//example.com//some/path', ); }); @@ -1297,6 +1297,6 @@ test('doubleSlash3', (t) => { undefined, undefined, ), - 'http://library.kiwix.org/content/myzim_yyyy-mm/replay://example.com/so%3Fme/pa%3Fth/http://example.com//some/path', + 'http://library.kiwix.org/content/myzim_yyyy-mm/-/example.com/so%3Fme/pa%3Fth/http%3A//example.com//some/path', ); }); diff --git a/src/zimscraperlib/rewriting/url_rewriting.py b/src/zimscraperlib/rewriting/url_rewriting.py index d2f7fac2..2ea1eeb9 100644 --- a/src/zimscraperlib/rewriting/url_rewriting.py +++ b/src/zimscraperlib/rewriting/url_rewriting.py @@ -31,16 +31,22 @@ . This is NOT valid : "foo/part/file?question%3DIs%20there%20any%20%2B%20here%3F" Every ZIM path produced by `normalize` is prefixed with the constant `REPLAY_MARKER` -(`"replay://"`), e.g. "example.com/foo" becomes "replay://example.com/foo". wombat.js -computes its own replay-prefix ("wb_rel_prefix") by subtracting the serving origin from -the full URL of the page being served; when a ZIM is served with no extra "collection" -path segment (e.g. a bare `kiwix.app/`), that subtraction used to leave an empty -or single-`/` prefix, which degenerates a regex used by wombat.js's `innerHTML`/ -`outerHTML` getters into matching (and deleting) any `/text/` span anywhere in the page -(reported as openzim/zimit#589). The marker guarantees that prefix can never again be -empty or trivial, by construction. A `ZimPath` may also be built directly from an -unmarked value (see `ZimPath.check_validity`), so the marker is never assumed when -reading a `ZimPath` back, only ever added by `normalize` itself. +(`"-/"`), e.g. "example.com/foo" becomes "-/example.com/foo". wombat.js computes its +own replay-prefix ("wb_rel_prefix") by subtracting the serving origin from the full URL +of the page being served; when a ZIM is served with no extra "collection" path segment +(e.g. a bare `kiwix.app/`), that subtraction used to leave an empty or single-`/` +prefix, which degenerates a regex used by wombat.js's `innerHTML`/`outerHTML` getters +into matching (and deleting) any `/text/` span anywhere in the page (reported as +openzim/zimit#589). The marker guarantees that prefix can never again be empty or +trivial, by construction. `-` was chosen because it is never percent-encoded by `quote`/ +`encodeURIComponent` (unlike e.g. `:`, which some servers percent-encode in a redirect's +`Location` header, defeating the marker's purpose) and a hostname can never start with +one, but a single `-` alone would not be enough: wombat's regex is +`wb_rel_prefix + '[^/]+/'`, and without the trailing `/` the resulting `/-[^/]+/` is +still common enough in ordinary text (e.g. `/-1/`, `/-webkit-x/`) to misfire the same +way. A `ZimPath` may also be built directly from an unmarked value (see +`ZimPath.check_validity`), so the marker is never assumed when reading a `ZimPath` back, +only ever added by `normalize` itself. A ZIM path must never contain a `.` or `..` path segment: per RFC 3986 these "dot-segments" are resolved away by any URI consumer (including the reader turning a @@ -108,8 +114,10 @@ class AdditionalRule: # a ZIM served with no extra "collection" path segment (e.g. bare `kiwix.app/`) # made wombat.js's `wb_rel_prefix` degenerate to `''`/`'/'`, corrupting any # `innerHTML`/`outerHTML` read on the page (webrecorder/wombat, reported as -# openzim/zimit#589). -REPLAY_MARKER = "replay://" +# openzim/zimit#589). Kept deliberately short (`-` is never percent-encoded, unlike +# e.g. `:`) but not shorter: the trailing `/` is load-bearing, see `normalize`'s +# docstring for why a bare `-` would not be enough. +REPLAY_MARKER = "-/" _ENCODED_SLASH_RX = re.compile(r"%2f", re.IGNORECASE) @@ -273,7 +281,7 @@ def value(self) -> str: @classmethod def check_validity(cls, value: str) -> None: - parts = urlsplit(value.removeprefix(REPLAY_MARKER)) + parts = urlsplit(value) if parts.scheme: raise ValueError(f"Unexpected scheme in value: {value} {parts.scheme}") @@ -451,17 +459,16 @@ def get_document_uri(self, item_path: ZimPath, item_fragment: str) -> str: URI. """ - # strip the replay marker (if any) before parsing: urlsplit would otherwise - # misparse e.g. "replay://example.com/foo" as having an actual scheme - # ("replay") and hostname ("example.com"). Both item_path and article_path are - # stripped independently and consistently, so the marker (when present on - # both, as it normally is) simply cancels out as a shared leading segment and - # never needs to be reintroduced into the computed relative path. - unmarked_item_value = item_path.value.removeprefix(REPLAY_MARKER) + # REPLAY_MARKER contains no character that makes urlsplit misparse a scheme + # or hostname out of it (see REPLAY_MARKER's definition), so item_path and + # article_path can be used as-is: when both are marked, as they normally + # are, the marker is simply a shared leading segment that cancels out on its + # own in the relative-path computation below, the same way e.g. a shared + # hostname segment would. # a ZIM path is never URL-encoded, so a `#` in it is a literal character # (e.g. coming from a `%23` in original URL) and not a fragment delimiter - item_parts = urlsplit(unmarked_item_value, allow_fragments=False) + item_parts = urlsplit(item_path.value, allow_fragments=False) # item_path is both path + querystring, both will be url-encoded in the document # so that readers consider them as a whole and properly pass them to libzim @@ -470,9 +477,7 @@ def get_document_uri(self, item_path: ZimPath, item_fragment: str) -> str: item_url += "?" + item_parts.query # drop `.` segments of the article path, as PurePosixPath used to do article_path = "/".join( - part - for part in self.article_path.value.removeprefix(REPLAY_MARKER).split("/") - if part != "." + part for part in self.article_path.value.split("/") if part != "." ) article_dir = ( article_path.removesuffix("/") diff --git a/tests/rewriting/test_js_rewriting.py b/tests/rewriting/test_js_rewriting.py index 61de3363..97130d6c 100644 --- a/tests/rewriting/test_js_rewriting.py +++ b/tests/rewriting/test_js_rewriting.py @@ -344,9 +344,12 @@ def __init__( self.expected = self.wrap_import(self.expected_str) @staticmethod - # We want to import js stored in zim file as `_zim_static/__wb_module_decl.js` from - # `https://exemple.com/some/path/` so path is - # `../../../_zim_static/__wb_module_decl.js` + # We want to import js stored in zim file as `_zim_static/__wb_module_decl.js` + # (an unmarked ZimPath, not derived via normalize()) from the marked article path + # for `https://exemple.com/some/path/`, i.e. `-/exemple.com/some/path/` (4 + # segments once REPLAY_MARKER is counted as one of them, since the two paths + # don't share it as a common prefix here), so path is + # `../../../../_zim_static/__wb_module_decl.js` def wrap_import(text: str) -> str: """ A small wrapper to help us generate the expected content for modules. @@ -356,7 +359,7 @@ def wrap_import(text: str) -> str: """ return ( "import { window, globalThis, self, document, location, top, parent, " - 'frames, opener } from "../../../_zim_static/__wb_module_decl.js";\n' + 'frames, opener } from "../../../../_zim_static/__wb_module_decl.js";\n' f"{text}" ) diff --git a/tests/rewriting/test_url_rewriting.py b/tests/rewriting/test_url_rewriting.py index 15aefbbb..4b7736cf 100644 --- a/tests/rewriting/test_url_rewriting.py +++ b/tests/rewriting/test_url_rewriting.py @@ -1237,32 +1237,32 @@ def test_base_href( @pytest.mark.parametrize( "article_path, item_path, expected_uri", [ - # both marked (the normal case, as produced by normalize()): the marker is - # stripped from both sides before computing the relative path, so it is a - # shared leading segment and never appears in the computed href + # both marked (the normal case, as produced by normalize()): the marker + # is a shared leading segment between the two paths, canceling out on + # its own in the relative-path computation and never appearing in the + # computed href, the same way e.g. a shared hostname segment would ( ZimPath(REPLAY_MARKER + "kiwix.org/a/article/document.html"), ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), "foo.html", ), # article_path unmarked (e.g. a static asset path built directly, like - # `_zim_static/__wb_module_decl.js`), item_path marked: the marker is - # still stripped from item_path, so it never leaks into the output, but - # there is no shared prefix left to cancel out against the (always - # unmarked) `_zim_static/` article_path, same as before REPLAY_MARKER - # existed + # `_zim_static/__wb_module_decl.js`), item_path marked: there is no + # shared prefix to cancel out against the (always unmarked) + # `_zim_static/` article_path, so the marker shows up in the computed + # href, same as any other non-shared leading segment would ( ZimPath("_zim_static/"), ZimPath(REPLAY_MARKER + "kiwix.org/a/article/foo.html"), - "../kiwix.org/a/article/foo.html", + "../" + REPLAY_MARKER + "kiwix.org/a/article/foo.html", ), - # the reverse: article_path marked, item_path unmarked; same result as - # today since the marker is only ever a shared prefix when both sides - # have it + # the reverse: article_path marked, item_path unmarked; one more level + # than if article_path were unmarked too, since the marker segment + # itself must now be walked up through as well ( ZimPath(REPLAY_MARKER + "kiwix.org/a/article/document.html"), ZimPath("_zim_static/wombat.js"), - "../../../_zim_static/wombat.js", + "../../../../_zim_static/wombat.js", ), ], ) @@ -1388,6 +1388,11 @@ class TestZimPath: # just as valid as an unmarked one (REPLAY_MARKER + "content/index.html"), (REPLAY_MARKER + "index.html"), + # REPLAY_MARKER's `-` (not a valid scheme's first character) followed + # immediately by `/` makes it structurally impossible for urlsplit to + # detect a scheme or netloc in anything that follows the marker, so + # even a value that would otherwise be rejected is accepted once marked + (REPLAY_MARKER + "https://bob@acme.com"), ], ) def test_good_zim_path(self, path: str): @@ -1401,8 +1406,6 @@ def test_good_zim_path(self, path: str): ("mailto:bob@acme.com"), ("tel:+41.34.34"), ("mailto:https://bob@acme.com"), - # the REPLAY_MARKER prefix doesn't hide a genuinely bad scheme behind it - (REPLAY_MARKER + "https://bob@acme.com"), ], ) def test_bad_zim_path_scheme(self, path: str):