Loading freeze.go +118 Changes for freeze.go: 118 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -23,6 +23,11 @@ var cssURLRegexp = regexp.MustCompile(`url\(\s*['"]?([^'")]+)['"]?\s*\)`) var cssImportRegexp = regexp.MustCompile(`@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)['"]?\s*\)?`) var jsImportRegexp = regexp.MustCompile(`(?m)(?:\bimport\s+(?:[^'";]*?\s+from\s+)?|\bexport\s+[^'";]*?\s+from\s+|\bimport\s*\(\s*)['"]([^'"]+)['"]`) type jsStringLiteralSpan struct { start int end int } // Freeze runs against an isolated transient server so the crawl observes the // same BaseX routes as start, without depending on any already running service. func runFreeze(output, directory string, debug bool) error { Loading Loading @@ -218,6 +223,14 @@ func freezeSite(startURL, output string) error { _ = e.Request.Visit(u) } }) collector.OnHTML("[onclick]", func(e *colly.HTMLElement) { for _, ref := range inlineEventURLRefs(e.Attr("onclick")) { u := e.Request.AbsoluteURL(ref) if u != "" { _ = e.Request.Visit(u) } } }) collector.OnError(func(r *colly.Response, err error) { // Missing linked resources should not make freeze fail. Loading Loading @@ -352,6 +365,13 @@ func rewriteHTMLLinksToRelative(body []byte, currentURL *url.URL, contentType, o rewriteAttr("img[src]", "src", "image/*") rewriteAttr("source[src], video[src], audio[src], iframe[src]", "src", "") rewriteAttr("form[action]", "action", "text/html") doc.Find("[onclick]").Each(func(_ int, sel *goquery.Selection) { val, ok := sel.Attr("onclick") if !ok { return } sel.SetAttr("onclick", rewriteInlineEventURLs(currentURL, contentType, val, outputDir)) }) htmlText, err := doc.Html() if err != nil { Loading Loading @@ -434,6 +454,102 @@ func jsImportRefs(body []byte) []string { return refs } // Inline handlers can hide navigations that Colly will not see through normal // HTML attributes. Only URL-shaped local literals are returned so labels, // feature strings, and other window.open arguments are ignored. func inlineEventURLRefs(script string) []string { spans := jsStringLiteralSpans(script) refs := make([]string, 0, len(spans)) for _, span := range spans { ref := script[span.start:span.end] if isInlineEventLocalURLCandidate(ref) { refs = append(refs, ref) } } return refs } // Event attributes are JavaScript, but the freeze pass only rewrites plain // string literal URLs. Escaped or computed values are left unchanged because // preserving executable code is safer than guessing. func rewriteInlineEventURLs(currentURL *url.URL, currentContentType, script, outputDir string) string { spans := jsStringLiteralSpans(script) if len(spans) == 0 { return script } var b strings.Builder last := 0 for _, span := range spans { ref := script[span.start:span.end] if !isInlineEventLocalURLCandidate(ref) { continue } rewritten, err := relativeMirroredRef(currentURL, currentContentType, ref, "text/html", outputDir) if err != nil { continue } b.WriteString(script[last:span.start]) b.WriteString(rewritten) last = span.end } if last == 0 { return script } b.WriteString(script[last:]) return b.String() } // This is a lightweight scanner, not a JavaScript parser. It handles quoted // literals well enough for inline attributes and skips escaped delimiters so // replacement offsets remain stable. func jsStringLiteralSpans(script string) []jsStringLiteralSpan { var spans []jsStringLiteralSpan for i := 0; i < len(script); i++ { quote := script[i] if quote != '\'' && quote != '"' && quote != '`' { continue } start := i + 1 for j := start; j < len(script); j++ { if script[j] == '\\' { j++ continue } if script[j] == quote { spans = append(spans, jsStringLiteralSpan{start: start, end: j}) i = j break } } } return spans } // The filter is intentionally conservative: it admits local-looking URL // strings and rejects schemes or whitespace-heavy values that are more likely // to be text, JavaScript options, or non-fetching browser actions. func isInlineEventLocalURLCandidate(ref string) bool { trimmed := strings.TrimSpace(ref) if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.Contains(trimmed, "\\") { return false } if strings.ContainsAny(trimmed, " \t\r\n") { return false } lower := strings.ToLower(trimmed) if strings.HasPrefix(lower, "mailto:") || strings.HasPrefix(lower, "javascript:") || strings.HasPrefix(lower, "tel:") || strings.HasPrefix(lower, "data:") { return false } if strings.HasPrefix(trimmed, "/") || strings.HasPrefix(trimmed, "./") || strings.HasPrefix(trimmed, "../") || strings.HasPrefix(trimmed, "?") { return true } if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { return true } return strings.Contains(trimmed, "/") } // Keep JavaScript rewriting limited to literal module specifiers. Computed // dynamic imports and bare packages are preserved because changing them would be // more likely to break application code than to make the frozen copy complete. Loading @@ -456,6 +572,8 @@ func rewriteJSImportsToRelative(body []byte, currentURL *url.URL, contentType, o return []byte(jsText), nil } // Bare module names are resolver inputs, not files the MaX server can mirror. // Only relative and root-relative specifiers should become crawl targets. func isLocalImportSpecifier(ref string) bool { trimmed := strings.TrimSpace(ref) if trimmed == "" { Loading main.go +1 −1 Changes for main.go: 1 added line, 1 removed line. Original line number Diff line number Diff line Loading @@ -10,7 +10,7 @@ import ( //go:embed max_releases.json var fallbackReleases []byte const version = "0.4.8" const version = "0.4.9" const maxConfigFile = "config.xml" const minSupportedMaxVersion = "0.0.5" Loading main_test.go +75 Changes for main_test.go: 75 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -54,6 +54,30 @@ func TestRewriteHTMLLinksToRelative(t *testing.T) { } } func TestRewriteHTMLOnclickLinksToRelative(t *testing.T) { currentURL, err := url.Parse("http://localhost:8080/section/index.html") if err != nil { t.Fatal(err) } query := "link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48" target := "/lanfranc/mirador/?" + query hash := sha1Hex(query)[:8] input := []byte(`<html><body><button onclick="window.open('` + strings.ReplaceAll(target, "&", "&") + `','Mirador Viewer','width=800,height=600,location=no')">Open</button></body></html>`) out, err := rewriteHTMLLinksToRelative(input, currentURL, "text/html", "/tmp/freeze") if err != nil { t.Fatal(err) } text := string(out) expected := `../lanfranc/mirador/index_q` + hash + `.html` if !strings.Contains(text, expected) { t.Fatalf("expected rewritten onclick URL %q, got: %s", expected, text) } if strings.Contains(text, "/lanfranc/mirador/?") { t.Fatalf("expected original onclick URL to be replaced, got: %s", text) } } func TestRewriteCSSLinksToRelative(t *testing.T) { currentURL, err := url.Parse("http://localhost:8080/assets/css/main.css") if err != nil { Loading Loading @@ -246,6 +270,15 @@ import "bare-package";`) } } func TestInlineEventURLRefs(t *testing.T) { script := `window.open('/lanfranc/mirador/?link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48','Mirador Viewer','width=800,height=600,location=no')` got := inlineEventURLRefs(script) want := []string{"/lanfranc/mirador/?link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48"} if strings.Join(got, ",") != strings.Join(want, ",") { t.Fatalf("unexpected onclick refs: want %v, got %v", want, got) } } func TestFreezeSiteCrawlsJSImports(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { Loading Loading @@ -282,6 +315,48 @@ func TestFreezeSiteCrawlsJSImports(t *testing.T) { } } func TestFreezeSiteCrawlsOnclickLocalLinks(t *testing.T) { query := "link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/": w.Header().Set("Content-Type", "text/html") target := "/lanfranc/mirador/?" + query _, _ = w.Write([]byte(`<button onclick="window.open('` + strings.ReplaceAll(target, "&", "&") + `','Mirador Viewer','width=800,height=600,location=no')">Open</button>`)) case "/lanfranc/mirador/": if r.URL.RawQuery != query { http.Error(w, "unexpected query", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html") _, _ = w.Write([]byte(`<p>mirador</p>`)) default: http.NotFound(w, r) } })) defer server.Close() output := t.TempDir() if err := freezeSite(server.URL+"/", output); err != nil { t.Fatal(err) } hash := sha1Hex(query)[:8] miradorPath := filepath.Join(output, "lanfranc", "mirador", "index_q"+hash+".html") if !fileExists(miradorPath) { t.Fatalf("expected frozen onclick target to exist: %s", miradorPath) } indexBytes, err := os.ReadFile(filepath.Join(output, "index.html")) if err != nil { t.Fatal(err) } indexText := string(indexBytes) expected := `lanfranc/mirador/index_q` + hash + `.html` if !strings.Contains(indexText, expected) { t.Fatalf("expected rewritten onclick target %q, got: %s", expected, indexText) } } func TestProjectsJSONStorageLifecycle(t *testing.T) { tmpHome := t.TempDir() prevHome := userMaxDir Loading Loading
freeze.go +118 Changes for freeze.go: 118 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -23,6 +23,11 @@ var cssURLRegexp = regexp.MustCompile(`url\(\s*['"]?([^'")]+)['"]?\s*\)`) var cssImportRegexp = regexp.MustCompile(`@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)['"]?\s*\)?`) var jsImportRegexp = regexp.MustCompile(`(?m)(?:\bimport\s+(?:[^'";]*?\s+from\s+)?|\bexport\s+[^'";]*?\s+from\s+|\bimport\s*\(\s*)['"]([^'"]+)['"]`) type jsStringLiteralSpan struct { start int end int } // Freeze runs against an isolated transient server so the crawl observes the // same BaseX routes as start, without depending on any already running service. func runFreeze(output, directory string, debug bool) error { Loading Loading @@ -218,6 +223,14 @@ func freezeSite(startURL, output string) error { _ = e.Request.Visit(u) } }) collector.OnHTML("[onclick]", func(e *colly.HTMLElement) { for _, ref := range inlineEventURLRefs(e.Attr("onclick")) { u := e.Request.AbsoluteURL(ref) if u != "" { _ = e.Request.Visit(u) } } }) collector.OnError(func(r *colly.Response, err error) { // Missing linked resources should not make freeze fail. Loading Loading @@ -352,6 +365,13 @@ func rewriteHTMLLinksToRelative(body []byte, currentURL *url.URL, contentType, o rewriteAttr("img[src]", "src", "image/*") rewriteAttr("source[src], video[src], audio[src], iframe[src]", "src", "") rewriteAttr("form[action]", "action", "text/html") doc.Find("[onclick]").Each(func(_ int, sel *goquery.Selection) { val, ok := sel.Attr("onclick") if !ok { return } sel.SetAttr("onclick", rewriteInlineEventURLs(currentURL, contentType, val, outputDir)) }) htmlText, err := doc.Html() if err != nil { Loading Loading @@ -434,6 +454,102 @@ func jsImportRefs(body []byte) []string { return refs } // Inline handlers can hide navigations that Colly will not see through normal // HTML attributes. Only URL-shaped local literals are returned so labels, // feature strings, and other window.open arguments are ignored. func inlineEventURLRefs(script string) []string { spans := jsStringLiteralSpans(script) refs := make([]string, 0, len(spans)) for _, span := range spans { ref := script[span.start:span.end] if isInlineEventLocalURLCandidate(ref) { refs = append(refs, ref) } } return refs } // Event attributes are JavaScript, but the freeze pass only rewrites plain // string literal URLs. Escaped or computed values are left unchanged because // preserving executable code is safer than guessing. func rewriteInlineEventURLs(currentURL *url.URL, currentContentType, script, outputDir string) string { spans := jsStringLiteralSpans(script) if len(spans) == 0 { return script } var b strings.Builder last := 0 for _, span := range spans { ref := script[span.start:span.end] if !isInlineEventLocalURLCandidate(ref) { continue } rewritten, err := relativeMirroredRef(currentURL, currentContentType, ref, "text/html", outputDir) if err != nil { continue } b.WriteString(script[last:span.start]) b.WriteString(rewritten) last = span.end } if last == 0 { return script } b.WriteString(script[last:]) return b.String() } // This is a lightweight scanner, not a JavaScript parser. It handles quoted // literals well enough for inline attributes and skips escaped delimiters so // replacement offsets remain stable. func jsStringLiteralSpans(script string) []jsStringLiteralSpan { var spans []jsStringLiteralSpan for i := 0; i < len(script); i++ { quote := script[i] if quote != '\'' && quote != '"' && quote != '`' { continue } start := i + 1 for j := start; j < len(script); j++ { if script[j] == '\\' { j++ continue } if script[j] == quote { spans = append(spans, jsStringLiteralSpan{start: start, end: j}) i = j break } } } return spans } // The filter is intentionally conservative: it admits local-looking URL // strings and rejects schemes or whitespace-heavy values that are more likely // to be text, JavaScript options, or non-fetching browser actions. func isInlineEventLocalURLCandidate(ref string) bool { trimmed := strings.TrimSpace(ref) if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.Contains(trimmed, "\\") { return false } if strings.ContainsAny(trimmed, " \t\r\n") { return false } lower := strings.ToLower(trimmed) if strings.HasPrefix(lower, "mailto:") || strings.HasPrefix(lower, "javascript:") || strings.HasPrefix(lower, "tel:") || strings.HasPrefix(lower, "data:") { return false } if strings.HasPrefix(trimmed, "/") || strings.HasPrefix(trimmed, "./") || strings.HasPrefix(trimmed, "../") || strings.HasPrefix(trimmed, "?") { return true } if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { return true } return strings.Contains(trimmed, "/") } // Keep JavaScript rewriting limited to literal module specifiers. Computed // dynamic imports and bare packages are preserved because changing them would be // more likely to break application code than to make the frozen copy complete. Loading @@ -456,6 +572,8 @@ func rewriteJSImportsToRelative(body []byte, currentURL *url.URL, contentType, o return []byte(jsText), nil } // Bare module names are resolver inputs, not files the MaX server can mirror. // Only relative and root-relative specifiers should become crawl targets. func isLocalImportSpecifier(ref string) bool { trimmed := strings.TrimSpace(ref) if trimmed == "" { Loading
main.go +1 −1 Changes for main.go: 1 added line, 1 removed line. Original line number Diff line number Diff line Loading @@ -10,7 +10,7 @@ import ( //go:embed max_releases.json var fallbackReleases []byte const version = "0.4.8" const version = "0.4.9" const maxConfigFile = "config.xml" const minSupportedMaxVersion = "0.0.5" Loading
main_test.go +75 Changes for main_test.go: 75 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -54,6 +54,30 @@ func TestRewriteHTMLLinksToRelative(t *testing.T) { } } func TestRewriteHTMLOnclickLinksToRelative(t *testing.T) { currentURL, err := url.Parse("http://localhost:8080/section/index.html") if err != nil { t.Fatal(err) } query := "link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48" target := "/lanfranc/mirador/?" + query hash := sha1Hex(query)[:8] input := []byte(`<html><body><button onclick="window.open('` + strings.ReplaceAll(target, "&", "&") + `','Mirador Viewer','width=800,height=600,location=no')">Open</button></body></html>`) out, err := rewriteHTMLLinksToRelative(input, currentURL, "text/html", "/tmp/freeze") if err != nil { t.Fatal(err) } text := string(out) expected := `../lanfranc/mirador/index_q` + hash + `.html` if !strings.Contains(text, expected) { t.Fatalf("expected rewritten onclick URL %q, got: %s", expected, text) } if strings.Contains(text, "/lanfranc/mirador/?") { t.Fatalf("expected original onclick URL to be replaced, got: %s", text) } } func TestRewriteCSSLinksToRelative(t *testing.T) { currentURL, err := url.Parse("http://localhost:8080/assets/css/main.css") if err != nil { Loading Loading @@ -246,6 +270,15 @@ import "bare-package";`) } } func TestInlineEventURLRefs(t *testing.T) { script := `window.open('/lanfranc/mirador/?link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48','Mirador Viewer','width=800,height=600,location=no')` got := inlineEventURLRefs(script) want := []string{"/lanfranc/mirador/?link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48"} if strings.Join(got, ",") != strings.Join(want, ",") { t.Fatalf("unexpected onclick refs: want %v, got %v", want, got) } } func TestFreezeSiteCrawlsJSImports(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { Loading Loading @@ -282,6 +315,48 @@ func TestFreezeSiteCrawlsJSImports(t *testing.T) { } } func TestFreezeSiteCrawlsOnclickLocalLinks(t *testing.T) { query := "link=https://bl.digirati.io/iiif/ark:/81055/vdc_100062968260.0x000001&canvasId=&canvasIndex=48" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/": w.Header().Set("Content-Type", "text/html") target := "/lanfranc/mirador/?" + query _, _ = w.Write([]byte(`<button onclick="window.open('` + strings.ReplaceAll(target, "&", "&") + `','Mirador Viewer','width=800,height=600,location=no')">Open</button>`)) case "/lanfranc/mirador/": if r.URL.RawQuery != query { http.Error(w, "unexpected query", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html") _, _ = w.Write([]byte(`<p>mirador</p>`)) default: http.NotFound(w, r) } })) defer server.Close() output := t.TempDir() if err := freezeSite(server.URL+"/", output); err != nil { t.Fatal(err) } hash := sha1Hex(query)[:8] miradorPath := filepath.Join(output, "lanfranc", "mirador", "index_q"+hash+".html") if !fileExists(miradorPath) { t.Fatalf("expected frozen onclick target to exist: %s", miradorPath) } indexBytes, err := os.ReadFile(filepath.Join(output, "index.html")) if err != nil { t.Fatal(err) } indexText := string(indexBytes) expected := `lanfranc/mirador/index_q` + hash + `.html` if !strings.Contains(indexText, expected) { t.Fatalf("expected rewritten onclick target %q, got: %s", expected, indexText) } } func TestProjectsJSONStorageLifecycle(t *testing.T) { tmpHome := t.TempDir() prevHome := userMaxDir Loading