From 8337741004a1b280355c0091664c9c6ef28776a7 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Tue, 17 Nov 2026 14:30:33 +0000 Subject: [PATCH 1/2] Implement denormalize()/defuzzify() and wire extractOriginalURL to them Adds ArticleUrlRewriter.denormalize()/defuzzify() (and their JS ports) as a best-effort reverse of normalize()/the fuzzy rules, and patches vendored wombat.js so extractOriginalURL() defers to a new wb_info.extract_original_url_function hook, the same way rewriteUrl() already defers to wb_info.rewrite_function. This lets CSS url() reads, document.referrer, dynamically created elements, and location.replace()/.assign()/updateLocation recover a plausible original URL, none of which the previous, narrower Location-getter patch (superseded here) ever covered. Closes #396. --- CHANGELOG.md | 6 + javascript/src/wombatSetup.js | 110 +++++++++++++++++- javascript/test/denormalize.js | 69 +++++++++++ rules/generate_rules.py | 66 ++++++++++- rules/patch_wombat.py | 99 +++++++--------- rules/rules.yaml | 104 ++++++++++++++++- src/zimscraperlib/rewriting/url_rewriting.py | 103 +++++++++++++++- tests/rewriting/test_url_rewriting.py | 116 +++++++++++++++++++ 8 files changed, 610 insertions(+), 63 deletions(-) create mode 100644 javascript/test/denormalize.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d7943724..a2090ce3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `VideoWebmMedium` preset: VP9 at 240k with the height capped at 720, a middle ground between `VideoWebmLow` and `VideoWebmHigh` (#271) +- `ArticleUrlRewriter.denormalize`/`defuzzify` (and their JS ports in `wombatSetup.js`), the best-effort reverse of `normalize`/the fuzzy rules, reconstructing a plausible (not guaranteed exact) original URL from a ZIM path (#396) +- Patch vendored `wombat.js` so `extractOriginalURL` defers to a new `wb_info.extract_original_url_function` hook (the same way `rewriteUrl` already defers to `wb_info.rewrite_function`), letting it call `denormalize`/`defuzzify` for cases its own pywb-oriented heuristic can never handle: CSS `url()` reads, `document.referrer`, dynamically created elements, and `location.replace()`/`.assign()`/`updateLocation` (#396) ### Changed @@ -28,6 +30,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Detect `export const`/`let`/`var`/`function`/`async function`/`*` as module code (`EXPORT_RX` only recognized `export {...}`, `export default` and `export class`), fixing JS rewriting wrongly injecting a non-module `let arguments;` wrapper into ES modules using these common export forms, which is a syntax error in strict/module code (#387) - Fix JS URL rewriter confusing a percent-encoded `%2B` with a raw `+` in query strings (#389) - Patch vendored `wombat.js` so `retrieveWBOSRCAsURL` (the helper behind the above element-property fix) resolves a recorded original against the frame's true original URL (`wb_info.url`) instead of its replay-time `ownerDocument`, fixing it returning/using a URL under the wrong host for a page whose own URL was changed by a fuzzy rule (e.g. YouTube embeds), which broke playback (#398) + +### Removed + +- Patch vendored `wombat.js` so `location.href`/`.search`/`.pathname` prefer `wb_info.url` over `extractOriginalURL` (#382, webrecorder/wombat#244): superseded by the new, more general `extract_original_url_function` hook above, which also covers `location.replace()`/`.assign()`/`updateLocation`, CSS, referrer and dynamic elements that the narrower patch never did (#396) - Add a host-gated `SITE_JS_PATCHES` mechanism to `JsRewriter`, fixing MDN's `` widget missing a deterministic `permalink` attribute (#394) - Polyfill `crypto.randomUUID()` when missing in a non-secure context (plain HTTP, non-`localhost`) (#391) - Polyfill `crypto.subtle.digest()` (SHA-1/SHA-256) when missing in a non-secure context (#393) diff --git a/javascript/src/wombatSetup.js b/javascript/src/wombatSetup.js index f7457320..8650dbd5 100644 --- a/javascript/src/wombatSetup.js +++ b/javascript/src/wombatSetup.js @@ -1,4 +1,4 @@ -import { fuzzyRules } from './fuzzyRules.js'; +import { fuzzyRules, defuzzyRules } from './fuzzyRules.js'; import URI from 'uri-js'; // Will be updated by rollup-plugin-version-injector @@ -257,6 +257,100 @@ export function escapeDotSegments(path) { .join('/'); } +export function unescapeDotSegments(path) { + // Reverse of escapeDotSegments: unescape a leading '_' added to a dot-segment. + return path + .split('/') + .map((part) => (part === '_.' || part === '_..' ? part.slice(1) : part)) + .join('/'); +} + +export function defuzzify(path) { + // Best-effort reverse of applyFuzzyRules: first matching unrule is applied and + // its result is immediately returned. Not guaranteed to recover the real + // original value: some fuzzy rules permanently discard information (e.g. the + // real hostname/subdomain or extra query keys), in which case this only + // rebuilds a plausible, representative value. + for (const rule of defuzzyRules) { + const new_path = path.replace(new RegExp(rule.match), rule.replace); + if (new_path != path) { + return new_path; + } + } + return path; +} + +// encodeURI already escapes a literal '%' (to '%25'), which is what we want: a +// literal '%' coming from an originally percent-encoded '%25' round-trips back +// correctly instead of staying an ambiguous, not-really-percent-encoded '%'. +// For a query string only, a literal '+' surviving encodeURI (which leaves it +// as-is) is escaped afterwards (to '%2B'), since '+' means a literal space in +// a query string (see urlRewriteFunction/denormalize) -- done *after* +// encodeURI, not before, so the '%' it would introduce isn't itself +// re-escaped by encodeURI. +function escapeForURI(part, { isQuery } = {}) { + const escaped = encodeURI(part); + return isQuery ? escaped.replaceAll('+', '%2B') : escaped; +} + +export function denormalize(zimPath) { + // Best-effort reverse of the host+path+query flattening done in + // urlRewriteFunction (see there for the forward direction this mirrors). + // Scheme is always reconstructed as 'https' (dropped on the way in, by + // normalize()/urlRewriteFunction, and never recoverable). Not guaranteed to + // recover the exact original URL, see defuzzify(). + const value = defuzzify(unescapeDotSegments(zimPath)); + + // host is always followed by a '/' starting the path, since normalize()/ + // urlRewriteFunction always ensure the path is non-empty (defaulting to '/') + const slashIndex = value.indexOf('/'); + let host = value.substring(0, slashIndex); + const rest = value.substring(slashIndex); + + // query, if any, starts at the first literal '?' normalize()/ + // urlRewriteFunction inserted; ambiguous only if the path itself legitimately + // contains a literal '?' (a valid, if rare, ZIM path shape), same best-effort + // caveat as fuzzy-rule lossiness + const queryIndex = rest.indexOf('?'); + const pathPart = queryIndex === -1 ? rest : rest.substring(0, queryIndex); + const queryPart = queryIndex === -1 ? null : rest.substring(queryIndex + 1); + + // an already-percent-encoded '/' (literal '%2F') is passed through as-is: it + // is already valid percent-encoding (an encoded slash within one segment), + // while every other '/' is a real path separator and must stay unescaped + const quotedPath = pathPart + .split('%2F') + .map((part) => escapeForURI(part)) + .join('%2F'); + const quotedQuery = + queryPart === null + ? '' + : '?' + escapeForURI(queryPart, { isQuery: true }).replaceAll('%20', '+'); + + if (!/^[\x00-\x7f]*$/.test(host)) { + const serializedHost = URI.serialize( + { scheme: 'http', host: host }, + { iri: false }, + ); + host = serializedHost.substring(7, serializedHost.length - 1); + } + + return `https://${host}${quotedPath}${quotedQuery}`; +} + +export function extractOriginalURLFunction(markedPath) { + // Called from the local wombat.js `extractOriginalURL` hook (see + // rules/patch_wombat.py), only once wombat has already stripped its own + // abs/rel replay prefix off the value, so `markedPath` should start with + // REPLAY_MARKER if (and only if) it is really one of ours. Returning + // `undefined` signals "not ours", letting wombat.js fall back to its own + // default (pywb-oriented) heuristic. + if (!markedPath.startsWith(REPLAY_MARKER)) { + return undefined; + } + return denormalize(markedPath.slice(REPLAY_MARKER.length)); +} + 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, @@ -482,6 +576,16 @@ export function getWombatInfo( doc, ), + // Local wombat.js patch (rules/patch_wombat.py): hooked into + // extractOriginalURL() as a fallback, called once wombat has already + // stripped its own abs/rel replay prefix off the value. Returning + // `undefined` signals "not ours", letting wombat.js fall back to its own + // default (pywb-oriented) heuristic -- unlike rewrite_function above, this + // is not an unconditional override, since extractOriginalURL legitimately + // sees many non-ZIM-path inputs. + extract_original_url_function: (strippedUrl) => + extractOriginalURLFunction(strippedUrl), + // Seems to be used only to send message to. We don't care ? top_url: current_url, @@ -550,6 +654,10 @@ export function getWombatInfo( export default { applyFuzzyRules: applyFuzzyRules, escapeDotSegments: escapeDotSegments, + unescapeDotSegments: unescapeDotSegments, + defuzzify: defuzzify, + denormalize: denormalize, + extractOriginalURLFunction: extractOriginalURLFunction, urlRewriteFunction: urlRewriteFunction, getWombatInfo: getWombatInfo, randomUUIDFromBytes: randomUUIDFromBytes, diff --git a/javascript/test/denormalize.js b/javascript/test/denormalize.js new file mode 100644 index 00000000..847e8d4a --- /dev/null +++ b/javascript/test/denormalize.js @@ -0,0 +1,69 @@ +import test from 'ava'; + +import { + REPLAY_MARKER, + escapeDotSegments, + unescapeDotSegments, + denormalize, + extractOriginalURLFunction, +} from '../src/wombatSetup.js'; + +test('unescapeDotSegments', (t) => { + t.is(unescapeDotSegments('a/_../b'), 'a/../b'); + t.is(unescapeDotSegments('a/_./b'), 'a/./b'); + t.is(unescapeDotSegments('_.'), '.'); + t.is(unescapeDotSegments('_..'), '..'); + t.is(unescapeDotSegments(''), ''); + // look-alikes are left untouched + t.is(unescapeDotSegments('a/.foo/b'), 'a/.foo/b'); + t.is(unescapeDotSegments('a/foo../b'), 'a/foo../b'); +}); + +test('escapeUnescapeDotSegmentsRoundtrip', (t) => { + for (const path of ['a/../b', 'a/./b', '..', '.', '', 'a/.foo/b']) { + t.is(unescapeDotSegments(escapeDotSegments(path)), path); + } +}); + +test('denormalizeRoundtrip', (t) => { + const cases = [ + ['example.com/', 'https://example.com/'], + ['example.com/resource', 'https://example.com/resource'], + ['example.com/a/_../b', 'https://example.com/a/../b'], + ['example.com/foo%2Fbar', 'https://example.com/foo%2Fbar'], + [ + 'example.com/résumé%2Frésumé', + 'https://example.com/r%C3%A9sum%C3%A9%2Fr%C3%A9sum%C3%A9', + ], + ['example.com/foo/bar?a=1&b=2', 'https://example.com/foo/bar?a=1&b=2'], + ]; + for (const [zimPath, expected] of cases) { + t.is(denormalize(zimPath), expected); + } +}); + +test('denormalizeLossy', (t) => { + // fuzzy-matched values can only be reconstructed to a plausible, + // representative value, not byte-identical to the real original + t.is( + denormalize('youtube.fuzzy.replayweb.page/videoplayback?id=1576'), + 'https://googlevideo.com/videoplayback?id=1576', + ); + // a query value's original `+`/`%20` (both decode to space) can't be told + // apart once normalized; `+` is always used when reconstructing + t.is( + denormalize('example.com/foo?q=a b c+d'), + 'https://example.com/foo?q=a+b+c%2Bd', + ); +}); + +test('extractOriginalURLFunctionMarked', (t) => { + t.is( + extractOriginalURLFunction(REPLAY_MARKER + 'example.com/foo/bar?a=1'), + 'https://example.com/foo/bar?a=1', + ); +}); + +test('extractOriginalURLFunctionUnmarkedFallsBackToUndefined', (t) => { + t.is(extractOriginalURLFunction('_zim_static/wombat.js'), undefined); +}); diff --git a/rules/generate_rules.py b/rules/generate_rules.py index 460e1b03..124a25d6 100644 --- a/rules/generate_rules.py +++ b/rules/generate_rules.py @@ -23,6 +23,10 @@ raise SystemExit("Fuzzy rule is missing a name") if "tests" not in rule or len(rule["tests"]) == 0: raise SystemExit("Fuzzy rule is missing test cases") + if "unreplace_pattern" not in rule or "unreplace" not in rule: + raise SystemExit( + f"Fuzzy rule {rule['name']} is missing unreplace_pattern/unreplace" + ) PY2JS_RULE_RX = re.compile(r"\\(\d)", re.ASCII) @@ -43,6 +47,14 @@ {% endfor %} ]; +export const defuzzyRules = [ +{% for rule in DEFUZZY_RULES %} { + match: '{{ rule['match'] }}', + replace: '{{ rule['replace'] }}', + }, +{% endfor %} +]; + """ js_parent = Path(__file__).joinpath("../../javascript/src").resolve() @@ -58,7 +70,14 @@ "replace": PY2JS_RULE_RX.sub(r"$\1", rule["replace"]), } for rule in FUZZY_RULES - ] + ], + DEFUZZY_RULES=[ + { + "match": rule["unreplace_pattern"].replace("\\", "\\\\"), + "replace": PY2JS_RULE_RX.sub(r"$\1", rule["unreplace"]), + } + for rule in FUZZY_RULES + ], ) ) logging.info("JS rules generation completed successfully") @@ -69,7 +88,7 @@ import test from 'ava'; -import { applyFuzzyRules } from '../src/wombatSetup.js'; +import { applyFuzzyRules, defuzzify } from '../src/wombatSetup.js'; {% for rule in FUZZY_RULES %} {% for test in rule['tests'] %} @@ -81,6 +100,16 @@ '{{test['raw_url'] if test['unchanged'] else test['fuzzified_url']}}', ); }); +{% if not test['unchanged'] %} +test('defuzzyrules_{{rule['name']}}_{{loop.index}}', (t) => { + t.is( + defuzzify( + '{{test['fuzzified_url']}}', + ), + '{{test['defuzzified_url']}}', + ); +}); +{% endif %} {% endfor %} {% endfor %} """ @@ -117,6 +146,14 @@ {% endfor %} ] +DEFUZZY_RULES = [ +{% for rule in FUZZY_RULES %} { + "pattern": r"{{ rule['unreplace_pattern'] }}", + "replace": r"{{ rule['unreplace'] }}", + }, +{% endfor %} +] + """ py_parent = Path(__file__).joinpath("../../src/zimscraperlib/rewriting").resolve() @@ -165,6 +202,31 @@ def test_fuzzyrules_{{ rule['name'] }}({{ rule['name'] }}_case: ContentForTests) ArticleUrlRewriter.apply_additional_rules({{ rule['name'] }}_case.input_str) == {{ rule['name'] }}_case.expected_str ) + + +@pytest.fixture( + params=[ +{% for test in rule['tests'] %} +{% if not test['unchanged'] %} + ContentForTests( + "{{ test['fuzzified_url'] }}", + "{{ test['defuzzified_url'] }}", + ), +{% endif %} +{% endfor %} + ] +) +def {{ rule['name'] }}_defuzzy_case(request: pytest.FixtureRequest): + yield request.param + + +def test_defuzzyrules_{{ rule['name'] }}( + {{ rule['name'] }}_defuzzy_case: ContentForTests, +): + assert ( + ArticleUrlRewriter.defuzzify({{ rule['name'] }}_defuzzy_case.input_str) + == {{ rule['name'] }}_defuzzy_case.expected_str + ) {% endfor %} """ diff --git a/rules/patch_wombat.py b/rules/patch_wombat.py index e0d8a3af..90a16f4e 100644 --- a/rules/patch_wombat.py +++ b/rules/patch_wombat.py @@ -4,14 +4,21 @@ - fetch() converting POST (and other non-GET) requests to GET, the same way its XMLHttpRequest override already does (webrecorder/wombat#242). -- Location getters (`location.href`/`.pathname`/`.search`/...) preferring - `wb_info.url` over re-deriving a value via `extractOriginalURL` - (webrecorder/wombat#245). - Element properties (`img.src`, `script.src`, `link.href`, `a.href` and its derived `.pathname`/`.search`/..., `Attr.value`) not returning a server-side-rewriter-recorded original the same way `getAttribute` already does, and not forgetting that recorded original once the property is assigned (webrecorder/wombat#240). +- `extractOriginalURL()` deferring to a new `wb_info.extract_original_url_function` + hook, the same way `rewriteUrl()` already defers to `wb_info.rewrite_function`, + so our own `denormalize()`/`defuzzify()` (zimscraperlib.rewriting.url_rewriting, + javascript/src/wombatSetup.js) get a chance at reconstructing a plausible + original URL for cases `extractOriginalURL`'s own pywb-oriented heuristic can + never handle (our rewriting scheme doesn't embed an absolute URL the way pywb's + does) -- CSS `url()` reads, `document.referrer`, dynamically created elements, + and (unlike the narrower Location-getter patch this supersedes, previously here + for openzim/python-scraperlib#382, webrecorder/wombat#244) `location.replace()`/ + `.assign()`/`updateLocation` (openzim/python-scraperlib#396). This script is invoked via `execute_after` on the wombat.js `get_file` action in openzim.toml, right after wombat.js is downloaded, so it runs on every @@ -147,62 +154,37 @@ 'this.overridePropExtract(this.$wbwindow.Request.prototype,"referrer")}' ) -# --- WombatLocation constructor: record the initial served href ------- +# --- extractOriginalURL(): defer to a wb_info.extract_original_url_function hook # -# `t` is `orig_loc` (the real Location being wrapped) and `e` is the -# Wombat instance. The minifier folded the statements that precede the -# constructor's `for (var prop in orig_loc)` loop into that loop's -# iterable expression via the comma operator, so the insertion point -# (recording the served href this WombatLocation was created with) has to -# be added as one more term of that same comma expression. -LOC_CTOR_ORIGINAL = ( - "e.initLocOverride(this,this.orig_setter,this.orig_getter)," - "e.setLoc(this,t.href),t)this.hasOwnProperty(r)" -) - -LOC_CTOR_PATCHED = ( - "e.initLocOverride(this,this.orig_setter,this.orig_getter)," - "e.setLoc(this,t.href),this._wb_initial_href=t.href,t)this.hasOwnProperty(r)" -) - -# --- Location getters: prefer wb_info.url ------------------------------- -# -# `location.href`/`.pathname`/`.search`/... (and the equivalent anchor/area -# element properties, which share this same function) always re-derive -# their value from the real served href via `extractOriginalURL`, which can -# only reverse rewrites wombat itself performed. Our own urlRewriteFunction -# (javascript/src/wombatSetup.js) has to flatten a URL's path+query into one -# ZIM path string, escaping '?'/'&' into literal '%3F'/'%26' so they survive -# as path characters -- extractOriginalURL cannot reverse that, even though -# the real, correctly-delimited original URL is already available as -# `wb_info.url`. +# `extractOriginalURL` tries to recover the real original URL from a value +# wombat.js itself rewrote, but its heuristic only knows how to reverse a +# pywb-style rewrite (an absolute URL embedded after a timestamp-like +# segment) -- it cannot reverse our own urlRewriteFunction, which flattens a +# URL's host+path+query into one ZIM path string instead. This previously +# left several read paths (CSS `url()`, `document.referrer`, dynamically +# created elements, `location.replace()`/`updateLocation`) unable to recover +# anything useful; a narrower patch here used to special-case the `Location` +# *getters* only (webrecorder/wombat#244), which this supersedes. # -# `this.wombat` is only set on a WombatLocation (not on an anchor/area -# element), so this only kicks in for `location.*`, and only as long as the -# served href hasn't changed since `_wb_initial_href` was recorded above -# (i.e. no client-side navigation happened since): a `history.pushState()`/ -# `location.href = ...`/etc. still falls back to extractOriginalURL exactly -# as before, since wb_info.url has nothing to say about those. -GETLOC_ORIGINAL = ( - "b.prototype.makeGetLocProp=function(t,e){var r=this;return function(){" - "if(this._no_rewrite)return e.call(this,t);" - '"maybeHref"===t&&(t="href");' - 'var i=e.call(this,"href");' - 'return"href"===t?r.extractOriginalURL(i):"ancestorOrigins"===t?[]:' - '(this._orig_href!==i&&r.setLoc(this,i),this["_"+t])' - "}}" +# `e` is computed just above as the length of whatever abs/rel replay prefix +# was stripped off the front of `i` (the value being extracted); passing +# `i.substr(e)` hands our hook the value with that prefix already removed, so +# it only has to check for (and strip) REPLAY_MARKER itself. Returning +# `undefined` from the hook (e.g. the value isn't one of ours) falls through +# to the unmodified heuristic below, unlike `rewrite_function`'s unconditional +# override: `extractOriginalURL` legitimately sees many non-ZIM-path inputs. +EXTRACT_ORIGINAL_URL_ORIGINAL = ( + "e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this." + "wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix." + 'length:this.wb_rel_prefix?1:0;var o=i.indexOf("/http",e);' ) -GETLOC_PATCHED = ( - "b.prototype.makeGetLocProp=function(t,e){var r=this;return function(){" - "if(this._no_rewrite)return e.call(this,t);" - '"maybeHref"===t&&(t="href");' - 'var i=e.call(this,"href"),' - "k=this.wombat&&r.wb_info&&r.wb_info.url&&i===this._wb_initial_href;" - "return k&&(i=r.wb_info.url)," - '"href"===t?k?i:r.extractOriginalURL(i):"ancestorOrigins"===t?[]:' - '(this._orig_href!==i&&r.setLoc(this,i),this["_"+t])' - "}}" +EXTRACT_ORIGINAL_URL_PATCHED = ( + "e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this." + "wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix." + "length:this.wb_rel_prefix?1:0;if(this.wb_info.extract_original_url_function){" + "var c=this.wb_info.extract_original_url_function(i.substr(e));" + 'if(c!==undefined)return c}var o=i.indexOf("/http",e);' ) # --- Element properties: return and forget a recorded original -------- @@ -369,8 +351,11 @@ patches = [ ("fetch()/Request() POST-to-GET conversion", FETCH_ORIGINAL, FETCH_PATCHED), ("fetch()/Request() POST-to-GET conversion", REQUEST_ORIGINAL, REQUEST_PATCHED), - ("Location getters preferring wb_info.url", LOC_CTOR_ORIGINAL, LOC_CTOR_PATCHED), - ("Location getters preferring wb_info.url", GETLOC_ORIGINAL, GETLOC_PATCHED), + ( + "extractOriginalURL() deferring to extract_original_url_function", + EXTRACT_ORIGINAL_URL_ORIGINAL, + EXTRACT_ORIGINAL_URL_PATCHED, + ), ( "Element properties returning/forgetting a recorded original", RETRIEVE_WBOSRC_ORIGINAL, diff --git a/rules/rules.yaml b/rules/rules.yaml index ef5f87ea..7ae139c8 100644 --- a/rules/rules.yaml +++ b/rules/rules.yaml @@ -16,17 +16,35 @@ # # Generic rules are also ommitted on purpose, we don't need them # +# Each rule also carries `unreplace_pattern`/`unreplace`, used by `defuzzify()` (the +# best-effort reverse of `apply_additional_rules()`/fuzzification, used by +# `ArticleUrlRewriter.denormalize()`). `unreplace_pattern` matches the *fuzzified* output +# shape and `unreplace` rebuilds a plausible (not necessarily exact) original +# `host+path+query`, reusing a canonical representative hostname for whatever the forward +# rule's own hostname-matching group discarded. These are hand-authored rather than +# mechanically derived from `pattern`/`replace`: several rules concatenate backreferences +# with no literal separator in `replace` (e.g. `youtube_video_info`'s `\1\2`), which would +# make a generically-derived reverse regex ambiguous. A rule whose forward transformation +# drops information with no alternate host to fall back on (e.g. `trim_digits_only`, which +# only drops a trailing digit-only querystring) uses the never-matching pattern `(?!)` for +# `unreplace_pattern`, so `defuzzify()` correctly leaves its output unchanged instead of +# guessing. fuzzyRules: - name: googlevideo_com pattern: .*googlevideo.com/(videoplayback(?=\?)).*[?&](id=[^&]+).* replace: youtube.fuzzy.replayweb.page/\1?\2 + unreplace_pattern: youtube\.fuzzy\.replayweb\.page/(videoplayback)\?(id=[^&]+) + unreplace: googlevideo.com/\1?\2 tests: - raw_url: foobargooglevideo.com/videoplayback?id=1576&key=value fuzzified_url: youtube.fuzzy.replayweb.page/videoplayback?id=1576 + defuzzified_url: googlevideo.com/videoplayback?id=1576 - raw_url: foobargooglevideo.com/videoplayback?some=thing&id=1576 fuzzified_url: youtube.fuzzy.replayweb.page/videoplayback?id=1576 + defuzzified_url: googlevideo.com/videoplayback?id=1576 - raw_url: foobargooglevideo.com/videoplayback?some=thing&id=1576&key=value fuzzified_url: youtube.fuzzy.replayweb.page/videoplayback?id=1576 + defuzzified_url: googlevideo.com/videoplayback?id=1576 - raw_url: foobargooglevideo.com/videoplaybackandfoo?some=thing&id=1576&key=value unchanged: true # videoplayback is not followed by `?` - raw_url: foobargoogle_video.com/videoplaybackandfoo?some=thing&id=1576&key=value @@ -34,19 +52,27 @@ fuzzyRules: - name: youtube_video_info pattern: (?:www\.)?youtube(?:-nocookie)?\.com/(get_video_info\?).*(video_id=[^&]+).* replace: youtube.fuzzy.replayweb.page/\1\2 + unreplace_pattern: youtube\.fuzzy\.replayweb\.page/(get_video_info\?)(video_id=[^&]+) + unreplace: www.youtube.com/\1\2 tests: - raw_url: www.youtube.com/get_video_info?video_id=123ah fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: www.youtube.com/get_video_info?foo=bar&video_id=123ah fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: www.youtube.com/get_video_info?video_id=123ah&foo=bar fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: youtube.com/get_video_info?video_id=123ah fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: youtube-nocookie.com/get_video_info?video_id=123ah fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: www.youtube-nocookie.com/get_video_info?video_id=123ah fuzzified_url: youtube.fuzzy.replayweb.page/get_video_info?video_id=123ah + defuzzified_url: www.youtube.com/get_video_info?video_id=123ah - raw_url: www.youtube-nocookie.com/get_video_info?foo=bar unchanged: true # no video_id parameter - raw_url: www.youtubeqnocookie.com/get_video_info?video_id=123ah @@ -54,21 +80,30 @@ fuzzyRules: - name: youtube_thumbnails pattern: i\.ytimg\.com\/vi\/(.*?)\/.*?\.(\w*?)(?:\?.*|$) replace: i.ytimg.com.fuzzy.replayweb.page/vi/\1/thumbnail.\2 + unreplace_pattern: i\.ytimg\.com\.fuzzy\.replayweb\.page/vi/(.*?)/thumbnail\.(\w*) + unreplace: i.ytimg.com/vi/\1/thumbnail.\2 tests: - raw_url: i.ytimg.com/vi/-KpLmsAR23I/maxresdefault.jpg?sqp=-oaymwEmCIAKENAF8quKqQMa8AEB-AH-CYAC0AWKAgwIABABGHIgTyg-MA8=&rs=AOn4CLDr-FmDmP3aCsD84l48ygBmkwHg-g fuzzified_url: i.ytimg.com.fuzzy.replayweb.page/vi/-KpLmsAR23I/thumbnail.jpg + defuzzified_url: i.ytimg.com/vi/-KpLmsAR23I/thumbnail.jpg - raw_url: i.ytimg.com/vi/-KpLmsAR23I/maxresdefault.png?sqp=-oaymwEmCIAKENAF8quKqQMa8AEB-AH-CYAC0AWKAgwIABABGHIgTyg-MA8=&rs=AOn4CLDr-FmDmP3aCsD84l48ygBmkwHg-g fuzzified_url: i.ytimg.com.fuzzy.replayweb.page/vi/-KpLmsAR23I/thumbnail.png + defuzzified_url: i.ytimg.com/vi/-KpLmsAR23I/thumbnail.png - raw_url: i.ytimg.com/vi/-KpLmsAR23I/maxresdefault.jpg fuzzified_url: i.ytimg.com.fuzzy.replayweb.page/vi/-KpLmsAR23I/thumbnail.jpg + defuzzified_url: i.ytimg.com/vi/-KpLmsAR23I/thumbnail.jpg - raw_url: i.ytimg.com/vi/-KpLmsAR23I/max-res.default.jpg fuzzified_url: i.ytimg.com.fuzzy.replayweb.page/vi/-KpLmsAR23I/thumbnail.jpg + defuzzified_url: i.ytimg.com/vi/-KpLmsAR23I/thumbnail.jpg - name: trim_digits_only pattern: ([^?]+)\?[\d]+$ replace: \1 + unreplace_pattern: (?!) + unreplace: \1 tests: - raw_url: www.example.com/page?1234 fuzzified_url: www.example.com/page + defuzzified_url: www.example.com/page - raw_url: www.example.com/page?foo=1234 unchanged: true - raw_url: www.example.com/page1234 @@ -82,94 +117,137 @@ fuzzyRules: - name: youtubei pattern: (?:www\.)?youtube(?:-nocookie)?\.com\/(youtubei\/[^?]+).*(videoId[^&]+).* replace: youtube.fuzzy.replayweb.page/\1?\2 + unreplace_pattern: youtube\.fuzzy\.replayweb\.page/(youtubei/[^?]+)\?(videoId[^&]+) + unreplace: www.youtube.com/\1?\2 tests: - raw_url: www.youtube-nocookie.com/youtubei/page/?videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube-nocookie.com/youtubei/page/?videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube.com/youtubei/page/?videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: www.youtube.com/youtubei/page/?videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube.com/youtubei/page/videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube.com/youtubei/page/videoIdqqq=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoIdqqq=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoIdqqq=123ah - raw_url: youtube.com/youtubei/page/videoId=123ah&foo=bar fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube.com/youtubei/page/?foo=bar&videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/?videoId=123ah - raw_url: youtube.com/youtubei/page/foo=bar&videoId=123ah fuzzified_url: youtube.fuzzy.replayweb.page/youtubei/page/foo=bar&?videoId=123ah + defuzzified_url: www.youtube.com/youtubei/page/foo=bar&?videoId=123ah - raw_url: youtube.com/youtubei/?videoId=123ah unchanged: true - name: youtube_embed pattern: (?:www\.)?youtube(?:-nocookie)?\.com/embed/([^?]+).* replace: youtube.fuzzy.replayweb.page/embed/\1 + unreplace_pattern: youtube\.fuzzy\.replayweb\.page/embed/(.+) + unreplace: www.youtube.com/embed/\1 tests: - raw_url: www.youtube-nocookie.com/embed/foo fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo + defuzzified_url: www.youtube.com/embed/foo - raw_url: www.youtube-nocookie.com/embed/bar fuzzified_url: youtube.fuzzy.replayweb.page/embed/bar + defuzzified_url: www.youtube.com/embed/bar - raw_url: www.youtube-nocookie.com/embed/foo/bar fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo/bar + defuzzified_url: www.youtube.com/embed/foo/bar - raw_url: www.youtube.com/embed/foo fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo + defuzzified_url: www.youtube.com/embed/foo - raw_url: youtube.com/embed/foo fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo + defuzzified_url: www.youtube.com/embed/foo - raw_url: youtube-nocookie.com/embed/foo fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo + defuzzified_url: www.youtube.com/embed/foo - raw_url: youtube.com/embed/foo?bar=alice fuzzified_url: youtube.fuzzy.replayweb.page/embed/foo + defuzzified_url: www.youtube.com/embed/foo - name: vimeo_cdn_fix # custom warc2zim rule intended to fix Vimeo support pattern: .*(?:gcs-vimeo|vod|vod-progressive|vod-adaptive)\.akamaized\.net.*\/(.+?.mp4)\?.*range=(.*?)(?:&.*|$) replace: vimeo-cdn.fuzzy.replayweb.page/\1?range=\2 + unreplace_pattern: vimeo-cdn\.fuzzy\.replayweb\.page/(.+?\.mp4)\?range=(.*) + unreplace: vod.akamaized.net/\1?range=\2 tests: - raw_url: gcs-vimeo.akamaized.net/123.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod.akamaized.net/123.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod-progressive.akamaized.net/123.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod-adaptive.akamaized.net/123.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod.akamaized.net/123.mp4?foo=bar&range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod.akamaized.net/123.mp4?foo=bar&range=123-456&bar=foo fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod.akamaized.net/123.mp4?range=123-456&bar=foo fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: foovod.akamaized.net/123.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/123.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/123.mp4?range=123-456 - raw_url: vod.akamaized.net/1/23.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/23.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/23.mp4?range=123-456 - raw_url: vod.akamaized.net/a/23.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/23.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/23.mp4?range=123-456 - raw_url: vod.akamaized.net/foo/bar/23.mp4?range=123-456 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/23.mp4?range=123-456 + defuzzified_url: vod.akamaized.net/23.mp4?range=123-456 - raw_url: foo.akamaized.net/123.mp4?range=123-456 unchanged: true - name: vimeo_cdn pattern: .*(?:gcs-vimeo|vod|vod-progressive)\.akamaized\.net.*?\/([\d/]+.mp4)$ replace: vimeo-cdn.fuzzy.replayweb.page/\1 + unreplace_pattern: vimeo-cdn\.fuzzy\.replayweb\.page/(.+) + unreplace: vod.akamaized.net/\1 tests: - raw_url: vod.akamaized.net/23.mp4 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/23.mp4 + defuzzified_url: vod.akamaized.net/23.mp4 - raw_url: vod.akamaized.net/23/12332.mp4 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/23/12332.mp4 + defuzzified_url: vod.akamaized.net/23/12332.mp4 - raw_url: https://vod-progressive.akamaized.net/exp=1635528595~acl=%2Fvimeo-prod-skyfire-std-us%2F01%2F4423%2F13%2F347119375%2F1398505169.mp4~hmac=27c31f1990aab5e5429f7f7db5b2dcbcf8d2f5c92184d53102da36920d33d53e/vimeo-prod-skyfire-std-us/01/4423/13/347119375/1398505169.mp4 fuzzified_url: vimeo-cdn.fuzzy.replayweb.page/01/4423/13/347119375/1398505169.mp4 + defuzzified_url: vod.akamaized.net/01/4423/13/347119375/1398505169.mp4 - name: vimeo_player pattern: .*player.vimeo.com\/(video\/[\d]+)\?.* replace: vimeo.fuzzy.replayweb.page/\1 + unreplace_pattern: vimeo\.fuzzy\.replayweb\.page/(.+) + unreplace: player.vimeo.com/\1 tests: - raw_url: player.vimeo.com/video/1234?foo=bar fuzzified_url: vimeo.fuzzy.replayweb.page/video/1234 + defuzzified_url: player.vimeo.com/video/1234 - raw_url: foo.player.vimeo.com/video/1234?foo=bar fuzzified_url: vimeo.fuzzy.replayweb.page/video/1234 + defuzzified_url: player.vimeo.com/video/1234 - raw_url: player.vimeo.com/video/1234?foo fuzzified_url: vimeo.fuzzy.replayweb.page/video/1234 + defuzzified_url: player.vimeo.com/video/1234 - raw_url: player.vimeo.com/video/1/23?foo=bar unchanged: true - raw_url: player.vimeo.com/video/123a?foo=bar @@ -179,56 +257,78 @@ fuzzyRules: - name: i_vimeo_cdn pattern: .*i\.vimeocdn\.com\/(.*)\?.* replace: i.vimeocdn.fuzzy.replayweb.page/\1 + unreplace_pattern: i\.vimeocdn\.fuzzy\.replayweb\.page/(.+) + unreplace: i.vimeocdn.com/\1 tests: - raw_url: i.vimeocdn.com/image/1234?foo=bar fuzzified_url: i.vimeocdn.fuzzy.replayweb.page/image/1234 + defuzzified_url: i.vimeocdn.com/image/1234 - raw_url: i.vimeocdn.com/something/a456?foo fuzzified_url: i.vimeocdn.fuzzy.replayweb.page/something/a456 + defuzzified_url: i.vimeocdn.com/something/a456 - name: cheatography_com pattern: cheatography\.com\/scripts\/(.*).js.*[?&](v=[^&]+).* replace: cheatography.com.fuzzy.replayweb.page/scripts/\1.js?\2 + unreplace_pattern: cheatography\.com\.fuzzy\.replayweb\.page/scripts/(.+)\.js\?(v=[^&]+) + unreplace: cheatography.com/scripts/\1.js?\2 tests: - raw_url: cheatography.com/scripts/useful.min.js?v=2&q=1719438924 fuzzified_url: cheatography.com.fuzzy.replayweb.page/scripts/useful.min.js?v=2 + defuzzified_url: cheatography.com/scripts/useful.min.js?v=2 - raw_url: cheatography.com/scripts/foo.js?v=2&q=1719438924 fuzzified_url: cheatography.com.fuzzy.replayweb.page/scripts/foo.js?v=2 + defuzzified_url: cheatography.com/scripts/foo.js?v=2 - raw_url: cheatography.com/scripts/useful.min.js?q=1719438924&v=2 fuzzified_url: cheatography.com.fuzzy.replayweb.page/scripts/useful.min.js?v=2 + defuzzified_url: cheatography.com/scripts/useful.min.js?v=2 - raw_url: cheatography.com/scripts/useful.min.js?q=1719438924&v=2&foo=bar fuzzified_url: cheatography.com.fuzzy.replayweb.page/scripts/useful.min.js?v=2 + defuzzified_url: cheatography.com/scripts/useful.min.js?v=2 - name: der_postillon_com pattern: blogger.googleusercontent.com\/img\/(.*\.jpg)=.* replace: blogger.googleusercontent.com.fuzzy.replayweb.page/img/\1.resized + unreplace_pattern: blogger\.googleusercontent\.com\.fuzzy\.replayweb\.page/img/(.+)\.resized + unreplace: blogger.googleusercontent.com/img/\1 tests: - raw_url: blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlN4LY6kFVwL8-rinDWp3kJp1TowOVD8vq8TP8nl3Lf1sI-hx0DE1GQA1jw7DT7XvK3FjghzJ17_1pvyXyDBAV0vtigJRnFCNfMxnndBnN3NYoXUvKQQsQ7JTGXOSajdo0mNQIv8wss_AxPBMrR4-Dd_EEacV7ZMS3m_IL2dz0WsbbKn7FD7ntsfOe0JUq/s600-rw/tickerzugtier2.jpg=w487-h220-p-k-no-nu fuzzified_url: blogger.googleusercontent.com.fuzzy.replayweb.page/img/b/R29vZ2xl/AVvXsEjlN4LY6kFVwL8-rinDWp3kJp1TowOVD8vq8TP8nl3Lf1sI-hx0DE1GQA1jw7DT7XvK3FjghzJ17_1pvyXyDBAV0vtigJRnFCNfMxnndBnN3NYoXUvKQQsQ7JTGXOSajdo0mNQIv8wss_AxPBMrR4-Dd_EEacV7ZMS3m_IL2dz0WsbbKn7FD7ntsfOe0JUq/s600-rw/tickerzugtier2.jpg.resized + defuzzified_url: blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlN4LY6kFVwL8-rinDWp3kJp1TowOVD8vq8TP8nl3Lf1sI-hx0DE1GQA1jw7DT7XvK3FjghzJ17_1pvyXyDBAV0vtigJRnFCNfMxnndBnN3NYoXUvKQQsQ7JTGXOSajdo0mNQIv8wss_AxPBMrR4-Dd_EEacV7ZMS3m_IL2dz0WsbbKn7FD7ntsfOe0JUq/s600-rw/tickerzugtier2.jpg - raw_url: blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlN4LY6kFVwL8-rinDWp3kJp1TowOVD8vq8TP8nl3Lf1sI-hx0DE1GQA1jw7DT7XvK3FjghzJ17_1pvyXyDBAV0vtigJRnFCNfMxnndBnN3NYoXUvKQQsQ7JTGXOSajdo0mNQIv8wss_AxPBMrR4-Dd_EEacV7ZMS3m_IL2dz0WsbbKn7FD7ntsfOe0JUq/w72-h72-p-k-no-nu/tickerzugtier2.jpg unchanged: true - name: iranwire_com pattern: (iranwire\.com\/questions\/detail\/.*)\?.* replace: \1 + unreplace_pattern: (?!) + unreplace: \1 tests: - raw_url: iranwire.com/questions/detail/1723?&_=1721804954220 fuzzified_url: iranwire.com/questions/detail/1723 + defuzzified_url: iranwire.com/questions/detail/1723 - raw_url: iranwire.com/questions/detail/1725?foo=bar&_=1721804454220 fuzzified_url: iranwire.com/questions/detail/1725 + defuzzified_url: iranwire.com/questions/detail/1725 - name: lesbases_anct_gouv_fr pattern: ((?:www\.)?lesbases\.anct\.gouv\.fr\/[^?]*(?:\?[^#]*?)?)_rsc=[^&]+(.*) replace: \1_rsc=1\2 + unreplace_pattern: (?!) + unreplace: \1 tests: - raw_url: lesbases.anct.gouv.fr/mentions-legales?_rsc=ut8ee fuzzified_url: lesbases.anct.gouv.fr/mentions-legales?_rsc=1 + defuzzified_url: lesbases.anct.gouv.fr/mentions-legales?_rsc=1 - raw_url: www.lesbases.anct.gouv.fr/mentions-legales?_rsc=ut8ee fuzzified_url: www.lesbases.anct.gouv.fr/mentions-legales?_rsc=1 + defuzzified_url: www.lesbases.anct.gouv.fr/mentions-legales?_rsc=1 - raw_url: lesbases.anct.gouv.fr/?_rsc=ut8ee fuzzified_url: lesbases.anct.gouv.fr/?_rsc=1 + defuzzified_url: lesbases.anct.gouv.fr/?_rsc=1 - raw_url: lesbases.anct.gouv.fr/cgu?foo=bar&_rsc=ut8ee fuzzified_url: lesbases.anct.gouv.fr/cgu?foo=bar&_rsc=1 + defuzzified_url: lesbases.anct.gouv.fr/cgu?foo=bar&_rsc=1 - raw_url: lesbases.anct.gouv.fr/cgu?_rsc=ut8ee&foo=bar fuzzified_url: lesbases.anct.gouv.fr/cgu?_rsc=1&foo=bar + defuzzified_url: lesbases.anct.gouv.fr/cgu?_rsc=1&foo=bar - raw_url: lesbases.anct.gouv.fr/mentions-legales unchanged: true - raw_url: other.site.fr/mentions-legales?_rsc=ut8ee unchanged: true - - diff --git a/src/zimscraperlib/rewriting/url_rewriting.py b/src/zimscraperlib/rewriting/url_rewriting.py index 2ea1eeb9..01362040 100644 --- a/src/zimscraperlib/rewriting/url_rewriting.py +++ b/src/zimscraperlib/rewriting/url_rewriting.py @@ -78,6 +78,12 @@ and not url-encoded. '=' and ',' are kept unencoded because some sites (e.g. YouTube) embed scripts that parse their own script URL and expect these characters to appear literally in it. + +`ArticleUrlRewriter.denormalize` is the best-effort reverse of `normalize` +(reconstructing a plausible, not guaranteed exact, original URL from a ZIM path), +used by wombat.js's `extractOriginalURL` hook for cases (CSS `url()` reads, +`document.referrer`, dynamically created elements, ...) where no server-side-recorded +original value is available to fall back on. """ import re @@ -94,7 +100,7 @@ import idna from zimscraperlib import logger -from zimscraperlib.rewriting.rules import FUZZY_RULES +from zimscraperlib.rewriting.rules import DEFUZZY_RULES, FUZZY_RULES @dataclass @@ -108,6 +114,11 @@ class AdditionalRule: for rule in FUZZY_RULES ] +COMPILED_DEFUZZY_RULES = [ + AdditionalRule(match=re.compile(rule["pattern"]), replace=rule["replace"]) + for rule in DEFUZZY_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 @@ -141,6 +152,19 @@ def _unquote_path(path: str) -> str: return "%2F".join(unquote(part) for part in _ENCODED_SLASH_RX.split(path)) +def _requote_path(path: str) -> str: + """Requote a decoded ZIM path, keeping a literal '%2F' run unescaped + + Inverse of `_unquote_path`: splits on the still-literal, uppercase `%2F` runs + `_unquote_path` leaves behind (representing an originally-percent-encoded `/` + within a single path segment) and `quote`s everything else, so that a literal + `%2F` run is passed through as-is (it is already valid percent-encoding, meaning + an encoded slash) while any other character `_unquote_path` decoded (including a + literal `%` coming from an original `%25`) is correctly re-escaped. + """ + return "%2F".join(quote(part, safe="/") for part in path.split("%2F")) + + def _remove_dot_segments(path: str) -> str: """Remove '.' and '..' segments from a path, per RFC 3986 section 5.2.4 @@ -312,6 +336,7 @@ class ArticleUrlRewriter: """ additional_rules: ClassVar[list[AdditionalRule]] = COMPILED_FUZZY_RULES + additional_unrules: ClassVar[list[AdditionalRule]] = COMPILED_DEFUZZY_RULES def __init__( self, @@ -548,6 +573,21 @@ def escape_dot_segments(cls, path: str) -> str: for part in path.split("/") ) + @classmethod + def unescape_dot_segments(cls, path: str) -> str: + """Reverse `escape_dot_segments`: unescape a leading `_` added to a segment + + A segment matching `^_+\\.{1,2}$` (one or more leading `_`, an actual + dot-segment never appears since `escape_dot_segments` always adds at least + one `_`) has exactly one leading `_` stripped, e.g. `_.` becomes `.`, and + `__.` (an escaped, already-once-escaped, literal `_.` segment) becomes `_.`. + Segments which don't match this shape are left untouched. + """ + return "/".join( + part[1:] if re.match(r"^_+\.{1,2}$", part) else part + for part in path.split("/") + ) + @classmethod def apply_additional_rules(cls, uri: HttpUrl | str) -> str: """Apply additional rules on a URL or relative path @@ -563,6 +603,23 @@ def apply_additional_rules(cls, uri: HttpUrl | str) -> str: return match.expand(rule.replace) return value + @classmethod + def defuzzify(cls, value: str) -> str: + """Best-effort reverse of `apply_additional_rules` + + First matching `unreplace_pattern` (see `rules/rules.yaml`) is applied and + its `unreplace` expansion is returned. This is not guaranteed to recover the + real original value: some fuzzy rules permanently discard information (e.g. + the real hostname/subdomain or extra query keys), in which case `unreplace` + only rebuilds a plausible, representative value. + + If no additional unrule is matching, the input is returned as-is. + """ + for rule in cls.additional_unrules: + if match := rule.match.match(value): + return match.expand(rule.replace) + return value + @classmethod def normalize(cls, url: HttpUrl) -> ZimPath: """Transform a HTTP URL into a ZIM path to use as a entry's key. @@ -648,3 +705,47 @@ def normalize(cls, url: HttpUrl) -> ZimPath: return ZimPath( REPLAY_MARKER + ArticleUrlRewriter.escape_dot_segments(fuzzified_url) ) + + @classmethod + def denormalize(cls, path: ZimPath) -> HttpUrl: + """Best-effort reverse of `normalize`: reconstruct a plausible original URL + + This is not guaranteed to recover the exact original URL: fuzzy rules are + lossy by construction (e.g. `defuzzify` can only rebuild a representative + hostname/subdomain, and some discarded query keys are gone for good), and + the scheme is always reconstructed as `https` (the scheme is dropped by + `normalize` and never recoverable). Port is also always dropped (same + reason). + + Raises ValueError if `path` was never produced by `normalize` (i.e. its + value does not start with `REPLAY_MARKER`), since such a path has no + original URL to reconstruct (e.g. a static asset path like + `_zim_static/wombat.js`). + """ + if not path.value.startswith(REPLAY_MARKER): + raise ValueError(f"Cannot denormalize an unmarked ZIM path: {path.value}") + + value = path.value.removeprefix(REPLAY_MARKER) + value = ArticleUrlRewriter.unescape_dot_segments(value) + value = ArticleUrlRewriter.defuzzify(value) + + # host is always followed by a '/' starting the path, since `normalize` + # always ensures the path is non-empty (defaulting to '/') + host, _, rest = value.partition("/") + rest = "/" + rest + + # query, if any, starts at the first literal '?' `normalize` inserted; + # ambiguous only if the path itself legitimately contains a literal '?' + # (a valid, if rare, ZIM path shape, see module docstring), same best-effort + # caveat as fuzzy-rule lossiness + path_part, sep, query_part = rest.partition("?") + + quoted_path = _requote_path(path_part) + quoted_query = ( + f"?{quote(query_part, safe='=&').replace('%20', '+')}" if sep else "" + ) + + if not host.isascii(): + host = idna.encode(host).decode() + + return HttpUrl(f"https://{host}{quoted_path}{quoted_query}") diff --git a/tests/rewriting/test_url_rewriting.py b/tests/rewriting/test_url_rewriting.py index 4b7736cf..c599b494 100644 --- a/tests/rewriting/test_url_rewriting.py +++ b/tests/rewriting/test_url_rewriting.py @@ -201,6 +201,122 @@ def test_escape_dot_segments(self, path: str, expected: str): assert ArticleUrlRewriter.escape_dot_segments(path) == expected +class TestUnescapeDotSegments: + @pytest.mark.parametrize( + "path,expected", + [ + ("a/_../b", "a/../b"), + ("a/_./b", "a/./b"), + ("a/_..", "a/.."), + ("a/_.", "a/."), + ("a/_../_../b", "a/../../b"), + ("_.", "."), + ("_..", ".."), + ("", ""), + ("a/.foo/b", "a/.foo/b"), + ("a/foo../b", "a/foo../b"), + ("a/..foo/b", "a/..foo/b"), + ("a/.../b", "a/.../b"), + # the escaping ladder unwinds one level at a time + ("a/__./b", "a/_./b"), + ("a/__../b", "a/_../b"), + ("a/___./b", "a/__./b"), + ("a/___../b", "a/__../b"), + ("__.", "_."), + ("__..", "_.."), + ("a/_.../b", "a/_.../b"), + ], + ) + def test_unescape_dot_segments(self, path: str, expected: str): + assert ArticleUrlRewriter.unescape_dot_segments(path) == expected + + @pytest.mark.parametrize( + "path", + [ + "a/../b", + "a/./b", + "a/..", + "a/.", + ".", + "..", + "", + "a/.foo/b", + "a/foo../b", + "a/..foo/b", + "a/.../b", + "a/_./b", + "a/_../b", + "a/__./b", + "a/__../b", + ], + ) + def test_escape_unescape_dot_segments_roundtrip(self, path: str): + assert ( + ArticleUrlRewriter.unescape_dot_segments( + ArticleUrlRewriter.escape_dot_segments(path) + ) + == path + ) + + +class TestDenormalize: + @pytest.mark.parametrize( + "url", + [ + "https://example.com/", + "https://example.com/resource", + "https://example.com/resource/folder/sub.txt", + "https://example.com/resource/folder/sub?foo=bar", + "https://example.com/a/../b", + "https://example.com/a/_./b", + "https://example.com/foo%2Fbar", + "https://example.com/r%C3%A9sum%C3%A9%2Fr%C3%A9sum%C3%A9", + "https://example.com/?foo=ba+r", + "https://xn--exmple-cva.com/resource", + ], + ) + def test_denormalize_roundtrip(self, url: str): + # scheme is always normalized to https on the way back, and dropped port/ + # auth are never present in these cases, so a plain round-trip is expected + assert ( + ArticleUrlRewriter.denormalize( + ArticleUrlRewriter.normalize(HttpUrl(url)) + ).value + == url + ) + + @pytest.mark.parametrize( + "url,expected", + [ + # scheme is always reconstructed as https, port is always dropped + ("http://example.com:8080/resource", "https://example.com/resource"), + # fuzzy-matched values can only be reconstructed to a plausible, + # representative value, not byte-identical to the real original + ( + "http://foobargooglevideo.com/videoplayback?id=1576&key=value", + "https://googlevideo.com/videoplayback?id=1576", + ), + # a query value's original `+`/`%20` (both decode to space) can't be + # told apart once normalized; `+` is always used when reconstructing + ( + "https://example.com/foo?q=a+b%20c%2Bd", + "https://example.com/foo?q=a+b+c%2Bd", + ), + ], + ) + def test_denormalize_lossy(self, url: str, expected: str): + assert ( + ArticleUrlRewriter.denormalize( + ArticleUrlRewriter.normalize(HttpUrl(url)) + ).value + == expected + ) + + def test_denormalize_requires_marker(self): + with pytest.raises(ValueError, match="unmarked ZIM path"): + ArticleUrlRewriter.denormalize(ZimPath("_zim_static/wombat.js")) + + _empty_zimpath_set: set[ZimPath] = set() From 829b3fb32240f7ce64fc1b386b28e19a7bd5afb7 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Tue, 17 Nov 2026 15:17:10 +0000 Subject: [PATCH 2/2] Fix urlRewriteFunction double-marking fresh rewrites of original URLs head_insert.html's prefix deliberately already ends with REPLAY_MARKER (so wombat.js's own wb_rel_prefix stays non-degenerate), but urlRewriteFunction and isAlreadyPrefixed still assumed it didn't, adding the marker a second time whenever a never-before-seen URL got rewritten at runtime (a dynamic import() specifier, a location assignment, ...), producing a ZIM path with no matching entry. static_prefix had the opposite problem, needing the marker-free root since static assets are never normalize()'d. Also fixes extractOriginalURLFunction/denormalize, exercised while reproducing the above against a real page: wombat.js's extractOriginalURL hook hands it the value already stripped of the full prefix (REPLAY_MARKER included, for the same reason), not merely the serving root, and that value is still percent-encoded as served (only '/', '=' and ',' literal) rather than the plain ZIM path denormalize() expects. --- javascript/src/wombatSetup.js | 94 +++++++++++++++++++-------- javascript/test/denormalize.js | 49 ++++++++++++-- javascript/test/wombatSetup.js | 13 +++- javascript/test/wombatUrlRewriting.js | 9 ++- rules/patch_wombat.py | 24 +++++-- 5 files changed, 146 insertions(+), 43 deletions(-) diff --git a/javascript/src/wombatSetup.js b/javascript/src/wombatSetup.js index 8650dbd5..482934c3 100644 --- a/javascript/src/wombatSetup.js +++ b/javascript/src/wombatSetup.js @@ -228,6 +228,14 @@ if (typeof crypto !== 'undefined' && typeof crypto.subtle === 'undefined') { // `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. +// +// `prefix` (computed by head_insert.html, passed into `getWombatInfo` below) +// already ends with this marker -- deliberately, so that wombat.js's own +// `wb_rel_prefix` (derived from `wb_info.prefix`) is itself non-degenerate -- +// so `urlRewriteFunction`'s own output and `isAlreadyPrefixed` build/check a +// rewritten URL as `prefix + escapedPath` (no second marker added), and +// `static_prefix` (whose own real path never carries the marker) has to strip +// it back off first. export const REPLAY_MARKER = '-/'; export function applyFuzzyRules(path) { @@ -338,32 +346,52 @@ export function denormalize(zimPath) { return `https://${host}${quotedPath}${quotedQuery}`; } -export function extractOriginalURLFunction(markedPath) { +export function extractOriginalURLFunction(escapedPath) { // Called from the local wombat.js `extractOriginalURL` hook (see - // rules/patch_wombat.py), only once wombat has already stripped its own - // abs/rel replay prefix off the value, so `markedPath` should start with - // REPLAY_MARKER if (and only if) it is really one of ours. Returning - // `undefined` signals "not ours", letting wombat.js fall back to its own - // default (pywb-oriented) heuristic. - if (!markedPath.startsWith(REPLAY_MARKER)) { + // rules/patch_wombat.py), only once wombat has confirmed the value being + // extracted starts with its own wb_abs_prefix/wb_rel_prefix and has already + // stripped that off. Unlike isAlreadyPrefixed/urlRewriteFunction's own + // notion of "prefix" (which never includes REPLAY_MARKER on its own, see + // REPLAY_MARKER's docstring), wb_abs_prefix/wb_rel_prefix are derived from + // the *same* `wb_info.prefix` that already carries REPLAY_MARKER -- so that + // marker has *already* been consumed as part of stripping the prefix by + // the time this is called, and `escapedPath` here is the escaped ZIM path + // with no REPLAY_MARKER of its own. + // + // `escapedPath` is still the served, percent-encoded text (only '/', '=' + // and ',' are literal, see urlRewriteFunction's own encodeURIComponent + // chain) -- decode it once to get back the raw, dot-segment-escaped, + // fuzzified ZIM path `denormalize` expects (the same shape Python's + // `denormalize` takes a `ZimPath.value` as). A literal `%2F` representing + // an originally-escaped slash survived encoding as `%252F`, so this single + // decode correctly yields back `%2F`, not a bare slash. + // + // Wrapped in try/catch: the caller only knows the value started with our + // own prefix, not that what follows is actually a well-formed, normalize() + // -produced ZIM path; returning `undefined` on failure falls back to + // wombat.js's own default (pywb-oriented) heuristic instead of throwing. + try { + return denormalize(decodeURIComponent(escapedPath)); + } catch { return undefined; } - return denormalize(markedPath.slice(REPLAY_MARKER.length)); } 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). 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.startsWith(prefix + REPLAY_MARKER); + // `prefix` (as computed by head_insert.html, fed into getWombatInfo) already + // ends with REPLAY_MARKER -- that is deliberate, it is what keeps wombat.js's + // own wb_rel_prefix non-degenerate (see REPLAY_MARKER's own docstring) -- so + // checking for `prefix` alone (not `prefix + REPLAY_MARKER`) is what anchors + // this to something unique to this deployment: it cannot coincidentally match + // genuine, unrelated content, since a real site's URL can never contain our + // own host-and-serving-path prefix as a literal substring. Any url starting + // with it is unambiguously an already-rewritten, fully-prefixed absolute URL + // (e.g. one read back from `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.startsWith(prefix); } export function hasAlreadyBeenRewritten( @@ -447,10 +475,14 @@ export function urlRewriteFunction( ) return url; - // If url starts with prefix, we need to remove this prefix before applying usual - // rewrite rules - if (url.startsWith(prefix)) { - url = uri.scheme + '://' + url.substring(prefix.length); + // A url starting with our own root prefix but missing REPLAY_MARKER right + // after it (so not caught by isAlreadyPrefixed above) is not a genuinely + // original URL: unwrap our own root prefix from the front of it so it gets + // re-resolved and properly (re-)rewritten with the marker, instead of being + // mistaken for a real external host+path starting with "library.kiwix.org". + const prefixRoot = prefix.slice(0, -REPLAY_MARKER.length); + if (url.startsWith(prefixRoot)) { + url = uri.scheme + '://' + url.substring(prefixRoot.length); } // This is a hack to detect improper URL encoding ; proper detection should be @@ -519,10 +551,16 @@ export function urlRewriteFunction( // reader once this ZIM path is turned into a URI const escapedPath = escapeDotSegments(fuzzifiedPath); - // Reencode everything but '/' (we decode it afterwards for simplicity) + // Reencode everything but '/' (we decode it afterwards for simplicity). + // `prefix` already ends with REPLAY_MARKER (see isAlreadyPrefixed's comment), + // so it is not added again here -- doing so would double it, producing a + // path with no matching ZIM entry (e.g. for a URL rewritten fresh at runtime, + // such as a dynamic `import()` specifier or a `location` assignment, neither + // of which goes through the server-side HTML/CSS/JS rewriter where this + // can't happen). const finalUrl = prefix + - encodeURIComponent(REPLAY_MARKER + escapedPath) + encodeURIComponent(escapedPath) .replaceAll('%2F', '/') .replaceAll('%3D', '=') .replaceAll('%2C', ','); @@ -620,7 +658,9 @@ export function getWombatInfo( // This is the prefix on which we have stored our static files (needed by wombat). // Must not conflict with other url served. // Will be used by wombat to not rewrite back the url - static_prefix: prefix + '_zim_static/', + // Static files are not normalize()'d, so (unlike `prefix` itself) their own + // path never carries REPLAY_MARKER -- strip it back off here. + static_prefix: prefix.slice(0, -REPLAY_MARKER.length) + '_zim_static/', wombat_ts: '', diff --git a/javascript/test/denormalize.js b/javascript/test/denormalize.js index 847e8d4a..15b8497f 100644 --- a/javascript/test/denormalize.js +++ b/javascript/test/denormalize.js @@ -6,6 +6,7 @@ import { unescapeDotSegments, denormalize, extractOriginalURLFunction, + urlRewriteFunction, } from '../src/wombatSetup.js'; test('unescapeDotSegments', (t) => { @@ -57,13 +58,53 @@ test('denormalizeLossy', (t) => { ); }); -test('extractOriginalURLFunctionMarked', (t) => { +test('extractOriginalURLFunction', (t) => { + // `escapedPath` here is the value *after* wombat.js's extractOriginalURL + // hook has already stripped its own wb_abs_prefix/wb_rel_prefix off -- + // which, since those are derived from `wb_info.prefix` (itself already + // carrying REPLAY_MARKER), has already consumed the marker too: no + // REPLAY_MARKER of its own survives in `escapedPath` (see + // extractOriginalURLFunctionRealisticRoundtrip for the full, real path + // through urlRewriteFunction's own percent-encoding). t.is( - extractOriginalURLFunction(REPLAY_MARKER + 'example.com/foo/bar?a=1'), + extractOriginalURLFunction('example.com/foo/bar?a=1'), 'https://example.com/foo/bar?a=1', ); }); -test('extractOriginalURLFunctionUnmarkedFallsBackToUndefined', (t) => { - t.is(extractOriginalURLFunction('_zim_static/wombat.js'), undefined); +test('extractOriginalURLFunctionFallsBackToUndefinedOnBadInput', (t) => { + // A lone '%' is not valid percent-encoding; decodeURIComponent throws, + // and the hook must fall back to `undefined` (letting wombat.js's own + // default heuristic take over) instead of propagating the exception. + t.is(extractOriginalURLFunction('example.com/100%'), undefined); +}); + +test('extractOriginalURLFunctionRealisticRoundtrip', (t) => { + // Exercises the real path: urlRewriteFunction's served, percent-encoded + // output (only '/', '=' and ',' literal, see its own encodeURIComponent + // chain), stripped of the serving prefix exactly like the wombat.js + // extractOriginalURL hook does (`i.substr(e)`, which consumes + // REPLAY_MARKER along with the rest of the prefix), must decode back + // through extractOriginalURLFunction to the original URL -- in + // particular, a character folded into the path and then percent-escaped + // for serving (here the '?' in a query value containing a raw, + // un-encoded URL, as docs.python.org-style pages do, see + // openzim/warc2zim#471) must come back as a literal, not stay escaped. + const prefix = + 'http://library.kiwix.org/content/myzim_yyyy-mm/' + REPLAY_MARKER; + const originalUrl = + 'https://example.com/improve-page.html?pageurl=https:/other.example/foo'; + const rewritten = urlRewriteFunction( + prefix + 'example.com/index.html', + 'example.com', + 'https', + 'https://example.com/index.html', + prefix, + originalUrl, + undefined, + undefined, + undefined, + ); + t.true(rewritten.startsWith(prefix)); + t.is(extractOriginalURLFunction(rewritten.slice(prefix.length)), originalUrl); }); diff --git a/javascript/test/wombatSetup.js b/javascript/test/wombatSetup.js index c254d2c0..a9e8cdb8 100644 --- a/javascript/test/wombatSetup.js +++ b/javascript/test/wombatSetup.js @@ -1,7 +1,7 @@ import test from 'ava'; import nodeCrypto from 'node:crypto'; -import utils from '../src/wombatSetup.js'; +import utils, { REPLAY_MARKER } from '../src/wombatSetup.js'; function textBytes(s) { return new TextEncoder().encode(s); @@ -16,7 +16,10 @@ function toHex(bytes) { } test.beforeEach((t) => { - t.context.prefix = 'http://library.kiwix.org/content/myzim_yyyy-mm/'; + // `prefix` already carries REPLAY_MARKER, same as head_insert.html computes + // it (see REPLAY_MARKER's own docstring in wombatSetup.js for why). + t.context.prefix = + 'http://library.kiwix.org/content/myzim_yyyy-mm/' + REPLAY_MARKER; t.context.originalHost = 'www.example.com'; t.context.originalScheme = 'https'; }); @@ -164,7 +167,11 @@ test('nominalWbInfo', (t) => { t.is(wmInfo.prefix, t.context.prefix); t.is(wmInfo.proxy_magic, ''); t.is(wmInfo.request_ts, ''); - t.is(wmInfo.static_prefix, t.context.prefix + '_zim_static/'); + // static_prefix never carries REPLAY_MARKER (static assets aren't normalize()'d) + t.is( + wmInfo.static_prefix, + t.context.prefix.slice(0, -REPLAY_MARKER.length) + '_zim_static/', + ); t.is(wmInfo.target_frame, '___wb_replay_top_frame'); t.is(wmInfo.timestamp, ''); t.is(wmInfo.top_url, t.context.prefix + path); diff --git a/javascript/test/wombatUrlRewriting.js b/javascript/test/wombatUrlRewriting.js index 26df16ac..2ec1fb3f 100644 --- a/javascript/test/wombatUrlRewriting.js +++ b/javascript/test/wombatUrlRewriting.js @@ -1,9 +1,12 @@ import test from 'ava'; -import { urlRewriteFunction } from '../src/wombatSetup.js'; +import { urlRewriteFunction, REPLAY_MARKER } from '../src/wombatSetup.js'; test.beforeEach((t) => { - t.context.prefix = 'http://library.kiwix.org/content/myzim_yyyy-mm/'; + // `prefix` already carries REPLAY_MARKER, same as head_insert.html computes + // it (see REPLAY_MARKER's own docstring in wombatSetup.js for why). + t.context.prefix = + 'http://library.kiwix.org/content/myzim_yyyy-mm/' + REPLAY_MARKER; t.context.originalHost = 'www.example.com'; t.context.originalScheme = 'https'; t.context.documentPath = '/path1/resource1.html'; @@ -120,7 +123,7 @@ test('relativeLinkOnPageWithConsecutiveSlashesKeepsThem', (t) => { undefined, undefined, ), - t.context.prefix + '-/www.example.com/path1//other.html', + t.context.prefix + 'www.example.com/path1//other.html', ); }); diff --git a/rules/patch_wombat.py b/rules/patch_wombat.py index 90a16f4e..1ab19be1 100644 --- a/rules/patch_wombat.py +++ b/rules/patch_wombat.py @@ -167,11 +167,21 @@ # *getters* only (webrecorder/wombat#244), which this supersedes. # # `e` is computed just above as the length of whatever abs/rel replay prefix -# was stripped off the front of `i` (the value being extracted); passing -# `i.substr(e)` hands our hook the value with that prefix already removed, so -# it only has to check for (and strip) REPLAY_MARKER itself. Returning -# `undefined` from the hook (e.g. the value isn't one of ours) falls through -# to the unmodified heuristic below, unlike `rewrite_function`'s unconditional +# was stripped off the front of `i` (the value being extracted). The hook is +# only called when `i` genuinely started with one of those two prefixes (the +# same condition `e`'s own ternary just tested) -- the ternary's other two +# branches (`wb_rel_prefix?1:0`) mean "`i` did not match either prefix at +# all", in which case `i.substr(e)` would be a meaningless 0/1-character +# chop of an unrelated value, not one of our ZIM paths. +# +# `wb_abs_prefix`/`wb_rel_prefix` are themselves derived from `wb_info.prefix` +# (our `prefix`, which already carries REPLAY_MARKER, see REPLAY_MARKER's own +# docstring in wombatSetup.js), so by the time `i.substr(e)` is computed, that +# marker has *already* been consumed as part of the stripped prefix -- the +# hook therefore receives a plain escaped ZIM path, with no REPLAY_MARKER of +# its own to check for. Returning `undefined` from the hook (e.g. `i.substr(e)` +# doesn't decode into a well-formed ZIM path after all) falls through to the +# unmodified heuristic below, unlike `rewrite_function`'s unconditional # override: `extractOriginalURL` legitimately sees many non-ZIM-path inputs. EXTRACT_ORIGINAL_URL_ORIGINAL = ( "e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this." @@ -182,7 +192,9 @@ EXTRACT_ORIGINAL_URL_PATCHED = ( "e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this." "wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix." - "length:this.wb_rel_prefix?1:0;if(this.wb_info.extract_original_url_function){" + "length:this.wb_rel_prefix?1:0;if(this.wb_info.extract_original_url_function&&" + "(this.startsWith(i,this.wb_abs_prefix)||this.wb_rel_prefix&&this.startsWith(" + "i,this.wb_rel_prefix))){" "var c=this.wb_info.extract_original_url_function(i.substr(e));" 'if(c!==undefined)return c}var o=i.indexOf("/http",e);' )