From d385c324a5f82e9f8b9b217c56feda0b212a66f6 Mon Sep 17 00:00:00 2001 From: samgozman Date: Mon, 30 Nov 2026 08:47:53 +0400 Subject: [PATCH] fix: tell stale sessions to reload, skip unclearable challenges and block pages From a month of real usage: most failed reads came from a session still running refetch 0.3.0 days after 0.5.0 was installed, so the Wayback step never ran; headless Chrome spent 13 s on each of 5 challenges that never cleared; and a few rows were misclassified. - Stale sessions: the SessionStart note, fetch_page errors and doctor say when a newer refetch is installed next to the running one, and to run /reload-plugins or restart Claude Code. events.db records the refetch version on every row (schema v2, upgraded in place), and stats splits fetches by version when more than one shows up. - Challenges: headless Chrome gives a challenge 8 s to clear instead of the whole render timeout, and stops at once on a block page. - Block pages: Cloudflare's "you have been blocked", Imperva's incident page, F5 BIG-IP's rejection (served with HTTP 200) and Akamai's Access Denied are refusals, not challenges or pages: they skip headless Chrome and go to the Wayback Machine, and a snapshot of one is not a read. - Hook: Claude Code's own errors (usage limits, the auto mode classifier, a declined permission) are recorded as denied and get no nudge; a tiny reply from an API address is no longer "page needs JavaScript". Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++ cmd/refetch/archive.go | 3 ++ cmd/refetch/doctor.go | 30 +++--------- cmd/refetch/hook.go | 40 ++++++++++++++-- cmd/refetch/hook_test.go | 17 ++++++- cmd/refetch/main.go | 4 +- cmd/refetch/mcp.go | 6 ++- cmd/refetch/stale.go | 70 ++++++++++++++++++++++++++++ cmd/refetch/stale_test.go | 66 ++++++++++++++++++++++++++ fetch/detect.go | 20 ++++++++ fetch/detect_test.go | 39 ++++++++++++++++ fetch/fetch.go | 4 ++ fetch/testdata/cloudflare-block.html | 14 ++++++ fetch/testdata/f5-rejected.html | 1 + fetch/testdata/imperva-block.html | 1 + render/drive.go | 11 ++++- render/render_test.go | 18 +++++++ stats/stats.go | 9 +++- stats/stats_test.go | 22 +++++++++ stats/text.go | 3 ++ store/store.go | 59 ++++++++++++++++------- store/store_test.go | 56 ++++++++++++++++++++++ 22 files changed, 447 insertions(+), 51 deletions(-) create mode 100644 cmd/refetch/stale.go create mode 100644 cmd/refetch/stale_test.go create mode 100644 fetch/testdata/cloudflare-block.html create mode 100644 fetch/testdata/f5-rejected.html create mode 100644 fetch/testdata/imperva-block.html diff --git a/README.md b/README.md index de643f9..588337e 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,11 @@ unless you turn it on: `/plugin` → Marketplaces → refetch → Enable auto-update. New versions load on the next launch or `/reload-plugins`. To update by hand, run `claude plugin update refetch@refetch`. +A session that was open during an update keeps running the version it +started with. refetch says so when that session starts a new conversation +and when a fetch fails, and `refetch doctor` reports it. `refetch stats` +splits fetches by refetch version when more than one shows up. + ### Check the setup Ask Claude to run `refetch doctor`, or run it yourself. It checks the diff --git a/cmd/refetch/archive.go b/cmd/refetch/archive.go index 69e2af1..7c27f4a 100644 --- a/cmd/refetch/archive.go +++ b/cmd/refetch/archive.go @@ -153,6 +153,9 @@ func (fr *fetcher) snapshot(ctx context.Context, url string) (fetch.Page, time.T } if strings.Contains(got.ContentType, "html") { switch { + case fetch.BlockPage(got.Body): + got.Last.Outcome = fetch.OutcomeRefused + return got, ts, errors.New("the snapshot is a block page") case fetch.Challenge(http.StatusOK, got.Body): got.Last.Outcome = fetch.OutcomeChallenge return got, ts, errors.New("the snapshot is a challenge page") diff --git a/cmd/refetch/doctor.go b/cmd/refetch/doctor.go index e1edad7..322dd69 100644 --- a/cmd/refetch/doctor.go +++ b/cmd/refetch/doctor.go @@ -76,7 +76,7 @@ func archiveCheck(cfg config.Config) check { func versionCheck() check { bin := buildVersion() - plugin := os.Getenv("REFETCH_PLUGIN_VERSION") + plugin, newer := os.Getenv("REFETCH_PLUGIN_VERSION"), newerPlugin() switch { case plugin == "": return check{true, "version", "refetch " + bin + " (not run through the plugin)"} @@ -84,6 +84,8 @@ func versionCheck() check { return check{true, "version", "refetch " + bin + ", with the plugin files of a development checkout"} case strings.TrimPrefix(bin, "v") != plugin: return check{false, "version", fmt.Sprintf("binary %s, plugin %s: run /reload-plugins, or check REFETCH_BIN", bin, plugin)} + case newer != "": + return check{false, "version", fmt.Sprintf("this session runs refetch %s, but %s is installed: run /reload-plugins or restart Claude Code", plugin, newer)} } return check{true, "version", "refetch " + bin + ", same as the plugin"} } @@ -103,15 +105,15 @@ var ( // GitHub is not a setup problem, so it never fails the check. func updateCheck(ctx context.Context) check { current := cmp.Or(os.Getenv("REFETCH_PLUGIN_VERSION"), strings.TrimPrefix(buildVersion(), "v")) - cur, ok := minorVersion(current) - if !ok || current == "0.0.0" { // a checkout of main; only releases set a version + cur, ok := releaseVersion(current) + if !ok { // a checkout of main; only releases set a version return check{true, "updates", "not checked for a development build"} } latest, err := latestRelease(ctx) if err != nil { return check{true, "updates", "could not check for a newer release: " + err.Error()} } - lat, ok := minorVersion(latest) + lat, ok := releaseVersion(latest) switch { case !ok: return check{true, "updates", "could not read the latest release " + strconv.Quote(latest)} @@ -148,26 +150,6 @@ func latestRelease(ctx context.Context) (string, error) { return strings.TrimPrefix(rel.Tag, "v"), nil } -// minorVersion parses the major and minor numbers of a release version -// such as 1.2.3; development and snapshot builds do not parse. -func minorVersion(v string) ([2]int, bool) { - parts := strings.Split(v, ".") - if len(parts) != 3 { - return [2]int{}, false - } - var out [2]int - for i, p := range parts { - n, err := strconv.Atoi(p) - if err != nil || n < 0 { - return [2]int{}, false - } - if i < 2 { - out[i] = n - } - } - return out, true -} - func configCheck() check { path := config.Path() if _, err := os.Stat(path); err != nil { diff --git a/cmd/refetch/hook.go b/cmd/refetch/hook.go index e177b20..a5c8522 100644 --- a/cmd/refetch/hook.go +++ b/cmd/refetch/hook.go @@ -7,6 +7,7 @@ import ( "encoding/json/v2" "fmt" "io" + neturl "net/url" "os" "regexp" "strconv" @@ -109,6 +110,9 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string { h.debug(h.st.Rollup(ctx, h.now.Add(-store.Retention))) } prunePages(config.DataDir(), savedPagesAge) + if note := staleNote(); note != "" { + return standingGuidance + "\n" + note + } return standingGuidance case "PreToolUse": if isRead(in.Tool) { @@ -121,6 +125,15 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string { default: return "" } + if !stats.IsFetchPage(in.Tool) && !isRead(in.Tool) { + return "" + } + if in.Event == "PostToolUseFailure" && harnessError.MatchString(in.Error) { + for id, u := range readURLs(in) { + h.record(ctx, in, id, u, store.CallDenied, in.Error) + } + return "" + } if stats.IsFetchPage(in.Tool) { outcome, why := store.CallOK, "" if in.Event == "PostToolUseFailure" { @@ -129,9 +142,6 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string { h.record(ctx, in, in.ToolUseID, in.Input.URL, outcome, why) return "" } - if !isRead(in.Tool) { - return "" - } failed := detect(in) for id, u := range readURLs(in) { outcome, why := store.CallOK, "" @@ -160,7 +170,7 @@ func (h *hooker) recordAs(ctx context.Context, tool string, in hookInput, id, ur return } h.debug(h.st.RecordCall(ctx, store.ToolCall{ - Time: h.now, SessionID: in.SessionID, ToolUseID: id, Tool: tool, URL: url, Outcome: outcome, Error: why, + Time: h.now, SessionID: in.SessionID, ToolUseID: id, Tool: tool, URL: url, Outcome: outcome, Error: why, Version: strings.TrimPrefix(buildVersion(), "v"), })) } @@ -179,6 +189,12 @@ func readURLs(in hookInput) map[string]string { return out } +// harnessError matches a tool error from Claude Code itself (a usage limit, +// a permission prompt the user declined, the auto mode classifier), which +// says nothing about the page and is no failure for refetch to pick up. +var harnessError = regexp.MustCompile(`(?i)hit your [^.]{0,30}limit|usage limit|auto mode classifier|` + + `doesn't want to proceed|tool use was rejected|permission to use|interrupted by (the )?user`) + // summaryBlock matches the wording of a challenge or refusal page in the // text a read returned (WebFetch's summary or context-mode's preview). var summaryBlock = regexp.MustCompile(`(?i)just a moment|checking your browser|verify(ing)? (that )?you are (a )?human|` + @@ -245,7 +261,7 @@ func detect(in hookInput) []failure { return []failure{{in.Input.URL, "HTTP 202, likely a bot challenge"}} case r.Bytes < 128<<10 && summaryBlock.MatchString(r.Result): return []failure{{in.Input.URL, "challenge or block page"}} - case r.Bytes > 0 && (r.Bytes < 256 || (r.Bytes < 16<<10 && summaryNeedsJS.MatchString(r.Result))): + case r.Bytes > 0 && (r.Bytes < 256 && !apiURL(in.Input.URL) || (r.Bytes < 16<<10 && summaryNeedsJS.MatchString(r.Result))): return []failure{{in.Input.URL, "page needs JavaScript"}} case r.Bytes < 64<<10 && summaryEmpty.MatchString(r.Result): return []failure{{in.Input.URL, "page came back empty"}} @@ -277,6 +293,20 @@ func detect(in hookInput) []failure { return nil } +// apiURL reports an address that answers with data rather than a page (an +// api host or path, a .json or .xml file, format=json): a reply of a few +// bytes there is an empty result, not a JavaScript-only page. +func apiURL(raw string) bool { + u, err := neturl.Parse(raw) + if err != nil { + return false + } + path := strings.ToLower(u.Path) + return strings.HasPrefix(strings.ToLower(u.Hostname()), "api.") || strings.Contains(path, "/api") || + strings.HasSuffix(path, ".json") || strings.HasSuffix(path, ".xml") || + strings.EqualFold(u.Query().Get("format"), "json") +} + func tinyIndex(text string) bool { m := ctxSize.FindStringSubmatch(text) if m == nil { diff --git a/cmd/refetch/hook_test.go b/cmd/refetch/hook_test.go index b51ef06..3e77274 100644 --- a/cmd/refetch/hook_test.go +++ b/cmd/refetch/hook_test.go @@ -57,6 +57,16 @@ const ( "tool_input":{"url":"https://news.example.com/a"},"tool_response":[{"type":"text","text":"Source: ..."}]}` fetchPageFail = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"mcp__plugin_refetch_refetch__fetch_page","tool_use_id":"t12", "tool_input":{"url":"https://c.example.com/"},"error":"could not read https://c.example.com/: refused (HTTP 403, chrome_like client)"}` + webFetchLimit = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"WebFetch","tool_use_id":"t17", + "tool_input":{"url":"https://commons.example.org/wiki/File:Logo.svg"},"error":"You've hit your 5-hour limit · resets 11pm (Asia/Tbilisi)"}` + webFetchClassifier = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"WebFetch","tool_use_id":"t18", + "tool_input":{"url":"https://www.example.co.il/"},"error":"The server-side auto mode classifier gave no verdict for WebFetch: another call in this response was changed."}` + webFetchTinyJSON = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"WebFetch","tool_use_id":"t19", + "tool_input":{"url":"https://commons.example.org/w/api.php?action=query&list=search&format=json&srsearch=x"}, + "tool_response":{"bytes":120,"code":200,"codeText":"OK","result":"The search returned no results.","durationMs":300,"url":"https://commons.example.org/w/api.php"}}` + webFetchTinyHTML = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"WebFetch","tool_use_id":"t20", + "tool_input":{"url":"https://shell.example.com/"}, + "tool_response":{"bytes":120,"code":200,"codeText":"OK","result":"There is nothing on the page.","durationMs":300,"url":"https://shell.example.com/"}}` sessionStart = `{"session_id":"s1","hook_event_name":"SessionStart","source":"startup"}` bashPost = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"Bash","tool_use_id":"t13","tool_input":{"command":"ls"},"tool_response":{"stdout":"x"}}` ) @@ -94,6 +104,10 @@ func TestHookNudges(t *testing.T) { {"WebFetch empty summary", webFetchEmpty, []string{"page came back empty"}}, {"WebFetch timeout", webFetchTimeout, []string{"(timeout of 60000ms exceeded)"}}, {"WebFetch pre", webFetchPre, nil}, + {"WebFetch usage limit", webFetchLimit, nil}, + {"WebFetch auto mode classifier", webFetchClassifier, nil}, + {"WebFetch tiny JSON", webFetchTinyJSON, nil}, + {"WebFetch tiny HTML", webFetchTinyHTML, []string{"page needs JavaScript"}}, {"ctx 403", ctx403, []string{"ctx_fetch_and_index could not read https://c.example.com/ (HTTP 403)", "save: true"}}, {"ctx challenge preview", ctxChallenge, []string{"https://d.example.com/ (challenge or block page)"}}, {"ctx empty page", ctxJS, []string{"nearly empty"}}, @@ -130,6 +144,7 @@ func TestHookNudges(t *testing.T) { "t1": store.CallFailed, "t2": store.CallFailed, "t3": store.CallFailed, "t4": store.CallOK, "t5": store.CallFailed, "t6": store.CallStarted, "t7": store.CallFailed, "t10#0": store.CallOK, "t10#1": store.CallFailed, "t11": store.CallOK, "t12": store.CallFailed, "t14": store.CallOK, + "t17": store.CallDenied, "t18": store.CallDenied, "t19": store.CallOK, "t20": store.CallFailed, } for id, want := range checks { if byID[id].Outcome != want { @@ -143,7 +158,7 @@ func TestHookNudges(t *testing.T) { t.Error("Bash must not be recorded") } r := stats.Build(calls, nil, stats.Options{}, time.Now()) - if r.Failed != 10 || r.PickedUp != 2 || r.Resolved != 1 || r.StillFailed != 1 { + if r.Failed != 11 || r.PickedUp != 2 || r.Resolved != 1 || r.StillFailed != 1 { t.Errorf("funnel from hook rows: %+v", r) } } diff --git a/cmd/refetch/main.go b/cmd/refetch/main.go index edcc372..302fb6b 100644 --- a/cmd/refetch/main.go +++ b/cmd/refetch/main.go @@ -213,7 +213,7 @@ func (fr *fetcher) get(ctx context.Context, url string, mode renderMode) (fetch. for _, a := range p.Attempts { err := fr.st.RecordAttempt(context.WithoutCancel(ctx), store.Attempt{ Time: time.Now(), FetchID: id, Via: fr.via, URL: a.URL, Client: a.Client, Outcome: a.Outcome, - Status: a.Status, Bytes: a.Bytes, Duration: a.Duration, Error: a.Err, + Status: a.Status, Bytes: a.Bytes, Duration: a.Duration, Error: a.Err, Version: strings.TrimPrefix(buildVersion(), "v"), }) if err != nil && fr.stderr != nil { _, _ = fmt.Fprintln(fr.stderr, "refetch: could not record a fetch step:", err) @@ -450,6 +450,8 @@ func (fr *fetcher) renderAttempt(ctx context.Context, url, host string) (fetch.A a.Outcome, a.Err = fetch.OutcomeTimeout, err.Error() case err != nil: a.Outcome, a.Err = fetch.OutcomeError, err.Error() + case fetch.BlockPage(rp.DOM): + a.Outcome, a.Err = fetch.OutcomeRefused, "headless Chrome got the site's block page" case fetch.Challenge(http.StatusOK, rp.DOM): a.Outcome, a.Err = fetch.OutcomeChallenge, "headless Chrome got the challenge page too" case fetch.EmptyRendered(rp.DOM): diff --git a/cmd/refetch/mcp.go b/cmd/refetch/mcp.go index e1bbb4c..7181bca 100644 --- a/cmd/refetch/mcp.go +++ b/cmd/refetch/mcp.go @@ -64,7 +64,11 @@ func newServer(fr *fetcher, dataDir string) *mcp.Server { }, func(ctx context.Context, _ *mcp.CallToolRequest, in fetchInput) (*mcp.CallToolResult, any, error) { text, err := fetchPage(ctx, fr, dataDir, in) if err != nil { - return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil //nolint:nilerr // a tool error result for Claude, not a protocol error + msg := err.Error() + if note := staleNote(); note != "" { + msg += "\n" + note + } + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil } return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}}, nil, nil }) diff --git a/cmd/refetch/stale.go b/cmd/refetch/stale.go new file mode 100644 index 0000000..519f49a --- /dev/null +++ b/cmd/refetch/stale.go @@ -0,0 +1,70 @@ +package main + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strconv" + "strings" +) + +// newerPlugin returns the newest refetch version installed next to the +// plugin this process runs from, when it is newer than this one; else "". +// Claude Code keeps a session's plugin, MCP server and hooks on the version +// it started with, so a long session goes on running an old refetch after +// an update (Nov 2026: 0.3.0 for days after 0.5.0 came out). Only the +// versioned plugin cache (…/refetch/) has versions side by side. +func newerPlugin() string { + root, current := os.Getenv("REFETCH_PLUGIN_ROOT"), os.Getenv("REFETCH_PLUGIN_VERSION") + cur, ok := releaseVersion(current) + if !ok || root == "" || filepath.Base(root) != current { + return "" + } + cache := os.DirFS(filepath.Dir(root)) + entries, err := fs.ReadDir(cache, ".") + if err != nil { + return "" + } + best, bestV := "", cur + for _, e := range entries { + v, ok := releaseVersion(e.Name()) + if !ok || slices.Compare(v[:], bestV[:]) <= 0 { + continue + } + if _, err := fs.Stat(cache, e.Name()+"/.claude-plugin/plugin.json"); err == nil { + best, bestV = e.Name(), v + } + } + return best +} + +// staleNote tells Claude, and through it the user, that this session runs +// an older refetch than the one installed; "" when it does not. +func staleNote() string { + v := newerPlugin() + if v == "" { + return "" + } + return fmt.Sprintf("refetch %s is installed, but this Claude Code session still runs refetch %s, which it started with. "+ + "Tell the user to run /reload-plugins or restart Claude Code to use the new version.", v, os.Getenv("REFETCH_PLUGIN_VERSION")) +} + +// releaseVersion parses a release version such as 1.2.3; development and +// snapshot builds do not parse, and neither does main's 0.0.0. +func releaseVersion(v string) ([3]int, bool) { + parts := strings.Split(v, ".") + if len(parts) != 3 || v == "0.0.0" { + return [3]int{}, false + } + var out [3]int + for i, p := range parts { + n, err := strconv.Atoi(p) + if err != nil || n < 0 { + return [3]int{}, false + } + out[i] = n + } + return out, true +} diff --git a/cmd/refetch/stale_test.go b/cmd/refetch/stale_test.go new file mode 100644 index 0000000..88380ed --- /dev/null +++ b/cmd/refetch/stale_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/samgozman/refetch/config" +) + +// pluginCache lays out Claude Code's versioned plugin cache with the given +// versions installed, and returns its directory. +func pluginCache(t *testing.T, versions ...string) string { + t.Helper() + dir := filepath.Join(t.TempDir(), "cache", "refetch", "refetch") + for _, v := range versions { + if err := os.MkdirAll(filepath.Join(dir, v, ".claude-plugin"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, v, ".claude-plugin", "plugin.json"), []byte(`{"version":"`+v+`"}`), 0o600); err != nil { + t.Fatal(err) + } + } + return dir +} + +func TestNewerPlugin(t *testing.T) { + dir := pluginCache(t, "0.3.0", "0.5.0", "0.10.0") + if err := os.MkdirAll(filepath.Join(dir, "0.11.0"), 0o700); err != nil { // a half-installed version + t.Fatal(err) + } + for _, tc := range []struct{ root, version, want string }{ + {filepath.Join(dir, "0.3.0"), "0.3.0", "0.10.0"}, + {filepath.Join(dir, "0.10.0"), "0.10.0", ""}, + {filepath.Join(dir, "0.5.0"), "0.0.0", ""}, // a checkout of main + {t.TempDir(), "0.3.0", ""}, // a plugin outside the versioned cache + {"", "0.3.0", ""}, // not run through the plugin + {filepath.Join(dir, "0.3.0"), "0.3.0-rc.1", ""}, // not a release + } { + t.Setenv("REFETCH_PLUGIN_ROOT", tc.root) + t.Setenv("REFETCH_PLUGIN_VERSION", tc.version) + if got := newerPlugin(); got != tc.want { + t.Errorf("root %s, version %s: newerPlugin = %q, want %q", tc.root, tc.version, got, tc.want) + } + } +} + +func TestStaleSessionIsTold(t *testing.T) { + dir := pluginCache(t, "0.3.0", "0.5.0") + t.Setenv("REFETCH_PLUGIN_ROOT", filepath.Join(dir, "0.3.0")) + t.Setenv("REFETCH_PLUGIN_VERSION", "0.3.0") + t.Setenv("REFETCH_DATA", t.TempDir()) + h := hooker{cfg: config.Default(), now: time.Now(), debug: func(error) {}} + got := h.handle(t.Context(), parse(t, sessionStart)) + if !strings.Contains(got, "refetch 0.5.0 is installed") || !strings.Contains(got, "/reload-plugins") || !strings.Contains(got, "fetch_page") { + t.Errorf("SessionStart in a stale session: %q", got) + } + old := version + version = "0.3.0" + t.Cleanup(func() { version = old }) + if c := versionCheck(); c.ok || !strings.Contains(c.detail, "0.5.0 is installed") { + t.Errorf("doctor's version check: %+v", c) + } +} diff --git a/fetch/detect.go b/fetch/detect.go index e72a74d..50dec9d 100644 --- a/fetch/detect.go +++ b/fetch/detect.go @@ -37,6 +37,26 @@ func Challenge(status int, body []byte) bool { return len([]rune(Text(body, "text/html"))) < maxChallengeText } +// blockMarkers: Cloudflare, Imperva, F5 BIG-IP (served with HTTP 200). +var blockMarkers = []string{ + "sorry, you have been blocked", "request unsuccessful. incapsula incident id", + "the requested url was rejected. please consult with your administrator", +} + +// BlockPage reports a firewall's refusal page, which neither headless +// Chrome nor waiting gets past (Akamai's names a reference number). +func BlockPage(body []byte) bool { + if len(body) > 256<<10 { + return false + } + lower := strings.ToLower(string(body)) + akamai := strings.Contains(lower, "you don't have permission to access") && strings.Contains(lower, "reference #") + if !akamai && !slices.ContainsFunc(blockMarkers, func(m string) bool { return strings.Contains(lower, m) }) { + return false + } + return len([]rune(Text(body, "text/html"))) < maxChallengeText +} + var mountPoint = regexp.MustCompile(`(?i)]+id=["']?(root|app|__next|__nuxt|svelte|main)["']?[^>]*>\s*|]*>\s*`) var jsNotices = []string{ diff --git a/fetch/detect_test.go b/fetch/detect_test.go index d360972..5ccb729 100644 --- a/fetch/detect_test.go +++ b/fetch/detect_test.go @@ -51,6 +51,45 @@ func TestDetectFixtures(t *testing.T) { } } +func TestBlockPage(t *testing.T) { + for name, want := range map[string]bool{ + "cloudflare-block.html": true, "imperva-block.html": true, "f5-rejected.html": true, + "cloudflare-challenge.html": false, "datadome-captcha.html": false, "small-article.html": false, + } { + body, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + if got := BlockPage(body); got != want { + t.Errorf("%s: BlockPage = %v", name, got) + } + } + akamai := []byte(`Access Denied

Access Denied

` + + `You don't have permission to access "http://www.example.com/" on this server.

Reference #18.4f2e1302.1796013251.1a2b3c`) + if !BlockPage(akamai) { + t.Error("Akamai's Access Denied is a block page") + } + article := []byte(`

Why sites say "Sorry, you have been blocked"

` + + strings.Repeat("A firewall shows that page when a request looks automated, and the reader sees nothing else. ", 40) + + `

`) + if BlockPage(article) { + t.Error("an article quoting a block page is not one") + } +} + +func TestBlockPageOutcome(t *testing.T) { + const u = "https://www.example.co.il/" + body, err := os.ReadFile(filepath.Join("testdata", "f5-rejected.html")) + if err != nil { + t.Fatal(err) + } + f := &Fetcher{chrome: fake(map[string]page{u: {status: 200, body: string(body)}}, nil)} + p, err := f.Get(t.Context(), u) + if err == nil || p.Attempts[0].Outcome != OutcomeRefused { + t.Errorf("an F5 rejection served with HTTP 200: err = %v, attempts = %+v", err, p.Attempts) + } +} + func TestNeedsJSOutcome(t *testing.T) { const u = "https://app.example.com/" shell, err := os.ReadFile(filepath.Join("testdata", "react-shell.html")) diff --git a/fetch/fetch.go b/fetch/fetch.go index 3e3e5fe..a139084 100644 --- a/fetch/fetch.go +++ b/fetch/fetch.go @@ -156,6 +156,10 @@ func (f *Fetcher) try(ctx context.Context, p *Page, client, rawURL string) error a.Outcome = OutcomeTimeout } a.Err = err.Error() + case BlockPage(body): + // Before Challenge: Cloudflare's block page carries challenge markers. + a.Outcome = OutcomeRefused + err = blockedError(fmt.Sprintf("refused (block page, HTTP %d, %s client)", status, client)) case strings.EqualFold(r.mitigated, "challenge") || Challenge(status, body): a.Outcome = OutcomeChallenge err = blockedError(fmt.Sprintf("challenge page (HTTP %d, %s client)", status, client)) diff --git a/fetch/testdata/cloudflare-block.html b/fetch/testdata/cloudflare-block.html new file mode 100644 index 0000000..1403144 --- /dev/null +++ b/fetch/testdata/cloudflare-block.html @@ -0,0 +1,14 @@ + +Attention Required! | Cloudflare + + + +
+

Sorry, you have been blocked

+

You are unable to access example.co.il

+
+

Why have I been blocked?

+

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution.

+
+ +
diff --git a/fetch/testdata/f5-rejected.html b/fetch/testdata/f5-rejected.html new file mode 100644 index 0000000..66d8827 --- /dev/null +++ b/fetch/testdata/f5-rejected.html @@ -0,0 +1 @@ +Request RejectedThe requested URL was rejected. Please consult with your administrator.

Your support ID is: 18395349790712150364

[Go Back] diff --git a/fetch/testdata/imperva-block.html b/fetch/testdata/imperva-block.html new file mode 100644 index 0000000..94c2243 --- /dev/null +++ b/fetch/testdata/imperva-block.html @@ -0,0 +1 @@ + diff --git a/render/drive.go b/render/drive.go index bbc4af0..e366849 100644 --- a/render/drive.go +++ b/render/drive.go @@ -30,6 +30,10 @@ const ( settlePoll = 250 * time.Millisecond // how often the text is measured after load settleMax = 3 * time.Second // the longest wait for the text to stop changing recheckWait = time.Second // after a challenge or empty page, the wait for a reload + // challengeWait is how long a challenge gets to clear itself. One a + // browser passes is gone in a few seconds; the rest never clear, so the + // time left goes to the next step (Nov 2026: 0 of 5 cleared in 13 s). + challengeWait = 8 * time.Second ) // blockedURLs are ad and analytics hosts: a page reads the same without @@ -115,6 +119,7 @@ func (t *tab) load(ctx, pageCtx context.Context, rawURL string) (Page, error) { return Page{}, fmt.Errorf("headless Chrome could not load the page: %s", nav.ErrorText) } t.frame = nav.FrameID + start := time.Now() wait, stop := pageCtx, context.CancelFunc(func() {}) for round := 0; ; round++ { _, err := t.c.waitEvent(wait, t.session, "Page.loadEventFired") @@ -129,7 +134,11 @@ func (t *tab) load(ctx, pageCtx context.Context, rawURL string) (Page, error) { } t.settle(pageCtx) p, err := t.snapshot(ctx) - if err != nil || pageCtx.Err() != nil || captchaWall(p.DOM) || !fetch.Challenge(http.StatusOK, p.DOM) && !fetch.EmptyRendered(p.DOM) { + challenge := fetch.Challenge(http.StatusOK, p.DOM) + switch { + case err != nil, pageCtx.Err() != nil, captchaWall(p.DOM), fetch.BlockPage(p.DOM), + challenge && time.Since(start) >= challengeWait, + !challenge && !fetch.EmptyRendered(p.DOM): return p, err } wait, stop = context.WithTimeout(pageCtx, recheckWait) diff --git a/render/render_test.go b/render/render_test.go index 70ca33c..031787f 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -36,6 +36,11 @@ func site(t *testing.T) *httptest.Server { _, _ = w.Write([]byte(`Just a moment... `)) + case "/stuck": // a challenge that never clears + _, _ = w.Write([]byte(`Just a moment...

Checking your browser.

`)) + case "/blocked": + _, _ = w.Write([]byte(`Attention Required! | Cloudflare +

Sorry, you have been blocked

You are unable to access this site.

`)) case "/loading": // an iframe that never loads holds back the load event _, _ = w.Write([]byte(`

Secret word: fig

From the orchard notes.

`)) case "/tracked": @@ -131,6 +136,19 @@ func TestRenderJavaScriptAndChallenge(t *testing.T) { t.Logf("refused %d dials outside the test machine", outside.Load()) } +func TestRenderGivesUpOnStuckChallenges(t *testing.T) { + chrome := chromeOrSkip(t) + srv := site(t) + r := &Renderer{Chrome: chrome, Timeout: 30 * time.Second, dial: loopbackDial} + for path, limit := range map[string]time.Duration{"/stuck": challengeWait + 8*time.Second, "/blocked": 8 * time.Second} { + start := time.Now() + p, err := r.Render(t.Context(), srv.URL+path) + if took := time.Since(start); err != nil || took > limit || len(p.DOM) == 0 { + t.Errorf("%s: took %s (limit %s with a 30s timeout), err %v", path, took, limit, err) + } + } +} + func TestRenderGoesThroughThePublicOnlyDialer(t *testing.T) { chrome := chromeOrSkip(t) srv := site(t) diff --git a/stats/stats.go b/stats/stats.go index 495d1a8..2646316 100644 --- a/stats/stats.go +++ b/stats/stats.go @@ -54,6 +54,9 @@ type Fetches struct { OKBy map[string]int `json:"ok_by,omitempty"` FailedBy map[string]int `json:"failed_by,omitempty"` MedianMS int64 `json:"median_ms"` + // ByVersion counts fetches by the refetch version that ran them: a + // session keeps the version it started with after an update. + ByVersion map[string]int `json:"by_version,omitempty"` } // Headless counts the headless Chrome step: needed whenever the HTTP clients @@ -133,6 +136,7 @@ type fetch struct { headlessMS int64 last string // the last HTTP client outcome wayback string // the Wayback Machine step's outcome; "" when it did not run + version string // the refetch that ran it; "" before versions were recorded } // stepTwoWhy names a failed headless step for the still-failed breakdown. @@ -298,7 +302,7 @@ func groupFetches(attempts []store.Attempt) []fetch { if !ok { i = len(out) idx[a.FetchID] = i - out = append(out, fetch{url: a.URL, host: a.Host}) + out = append(out, fetch{url: a.URL, host: a.Host, version: a.Version}) } f := &out[i] f.end = a.Time @@ -340,10 +344,11 @@ func matchFetch(fetches []fetch, call store.ToolCall) fetch { } func summarize(fetches []fetch) Fetches { - s := Fetches{OKBy: map[string]int{}, FailedBy: map[string]int{}} + s := Fetches{OKBy: map[string]int{}, FailedBy: map[string]int{}, ByVersion: map[string]int{}} var ds []int64 for _, f := range fetches { s.Total++ + s.ByVersion[cmp.Or(f.version, "unrecorded")]++ ds = append(ds, f.durationMS) if f.ok { s.OK++ diff --git a/stats/stats_test.go b/stats/stats_test.go index 807fb60..cae2dbd 100644 --- a/stats/stats_test.go +++ b/stats/stats_test.go @@ -185,3 +185,25 @@ func TestWaybackStep(t *testing.T) { } } } + +func TestFetchesByVersion(t *testing.T) { + t0 := time.Date(2026, 11, 27, 12, 0, 0, 0, time.UTC) + at := func(id, version string) store.Attempt { + return store.Attempt{Time: t0, FetchID: id, URL: "https://x.com/" + id, Host: "x.com", Client: "chrome_like", Outcome: "ok", Version: version} + } + r := Build(nil, []store.Attempt{at("a", "0.6.0"), at("b", "0.6.0"), at("c", "")}, Options{Since: t0}, t0.Add(time.Minute)) + if r.Fetches.ByVersion["0.6.0"] != 2 || r.Fetches.ByVersion["unrecorded"] != 1 { + t.Errorf("by version = %v", r.Fetches.ByVersion) + } + var buf bytes.Buffer + r.WriteText(&buf, Header{Version: "dev"}) + if !strings.Contains(buf.String(), "by refetch version") || !strings.Contains(buf.String(), "0.6.0 2") { + t.Errorf("text lacks the version split:\n%s", buf.String()) + } + r = Build(nil, []store.Attempt{at("a", "0.6.0")}, Options{Since: t0}, t0.Add(time.Minute)) + buf.Reset() + r.WriteText(&buf, Header{Version: "dev"}) + if strings.Contains(buf.String(), "by refetch version") { + t.Errorf("one version needs no split:\n%s", buf.String()) + } +} diff --git a/stats/text.go b/stats/text.go index b0ed364..63c3178 100644 --- a/stats/text.go +++ b/stats/text.go @@ -73,6 +73,9 @@ func (r Report) WriteText(w io.Writer, h Header) { line(0, "Fetches (fetch_page and refetch get)", f.Total, "median "+millis(f.MedianMS)) line(1, "ok", f.OK, breakdown(okBy)) line(1, "failed", f.Total-f.OK, breakdown(f.FailedBy)) + if len(f.ByVersion) > 1 { + line(1, "by refetch version", f.Total, breakdown(f.ByVersion)) + } } if hd := r.Headless; hd.Needed > 0 { diff --git a/store/store.go b/store/store.go index c319607..0208f9a 100644 --- a/store/store.go +++ b/store/store.go @@ -41,6 +41,7 @@ type ToolCall struct { Outcome string Error string // first 300 characters CCVersion string // Claude Code version + Version string // refetch's version } // Attempt is one step inside a fetch_page call (or refetch get). @@ -56,6 +57,7 @@ type Attempt struct { Bytes int Duration time.Duration Error string // first 300 characters + Version string // refetch's version } // Store is an open events.db. @@ -75,7 +77,8 @@ CREATE TABLE IF NOT EXISTS tool_calls ( host TEXT NOT NULL DEFAULT '', outcome TEXT NOT NULL, error TEXT NOT NULL DEFAULT '', - cc_version TEXT NOT NULL DEFAULT '' + cc_version TEXT NOT NULL DEFAULT '', + version TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS tool_calls_ts ON tool_calls(ts); CREATE UNIQUE INDEX IF NOT EXISTS tool_calls_use ON tool_calls(tool_use_id) WHERE tool_use_id != ''; @@ -91,7 +94,8 @@ CREATE TABLE IF NOT EXISTS attempts ( status INTEGER NOT NULL DEFAULT 0, bytes INTEGER NOT NULL DEFAULT 0, ms INTEGER NOT NULL DEFAULT 0, - error TEXT NOT NULL DEFAULT '' + error TEXT NOT NULL DEFAULT '', + version TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS attempts_ts ON attempts(ts); CREATE TABLE IF NOT EXISTS daily ( @@ -103,7 +107,7 @@ CREATE TABLE IF NOT EXISTS daily ( n INTEGER NOT NULL, PRIMARY KEY (day, kind, name, outcome, host) ); -PRAGMA user_version = 1; +PRAGMA user_version = 2; ` // Path is events.db inside dir. @@ -133,6 +137,14 @@ func Open(ctx context.Context, path string) (*Store, error) { return &Store{db: db, path: path}, nil } +// addVersion adds the version columns to a version 1 file. Each ALTER may +// race another process's; a column already there counts as added. +var addVersion = []string{ + `ALTER TABLE tool_calls ADD COLUMN version TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE attempts ADD COLUMN version TEXT NOT NULL DEFAULT ''`, + `PRAGMA user_version = 2`, +} + // migrate applies the schema unless it is already there. Several processes // (hooks and MCP servers of parallel sessions) can create the file at the // same moment, and setting up a new file can return SQLITE_BUSY without @@ -141,10 +153,15 @@ func migrate(ctx context.Context, db *sql.DB) error { var err error for try := range 20 { var v int - if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&v); err == nil && v >= 1 { + if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&v); err == nil && v >= 2 { return nil } - if err == nil { + switch { + case err == nil && v == 1: + if err = upgrade(ctx, db); err == nil { + return nil + } + case err == nil: if _, err = db.ExecContext(ctx, schema); err == nil { return nil } @@ -161,6 +178,15 @@ func migrate(ctx context.Context, db *sql.DB) error { return err } +func upgrade(ctx context.Context, db *sql.DB) error { + for _, q := range addVersion { + if _, err := db.ExecContext(ctx, q); err != nil && !strings.Contains(err.Error(), "duplicate column") { + return err + } + } + return nil +} + // Close closes the database. func (s *Store) Close() error { return s.db.Close() } @@ -172,13 +198,14 @@ func (s *Store) File() string { return s.path } func (s *Store) RecordCall(ctx context.Context, c ToolCall) error { c.URL, c.Host = NormalizeURL(c.URL) _, err := s.db.ExecContext(ctx, ` - INSERT INTO tool_calls (ts, session_id, tool_use_id, tool, url, host, outcome, error, cc_version) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO tool_calls (ts, session_id, tool_use_id, tool, url, host, outcome, error, cc_version, version) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (tool_use_id) WHERE tool_use_id != '' DO UPDATE SET outcome = excluded.outcome, error = excluded.error, url = CASE WHEN excluded.url != '' THEN excluded.url ELSE url END, - host = CASE WHEN excluded.host != '' THEN excluded.host ELSE host END`, - ms(c.Time), c.SessionID, c.ToolUseID, c.Tool, c.URL, c.Host, c.Outcome, clip(scrubURLs(c.Error)), c.CCVersion) + host = CASE WHEN excluded.host != '' THEN excluded.host ELSE host END, + version = excluded.version`, + ms(c.Time), c.SessionID, c.ToolUseID, c.Tool, c.URL, c.Host, c.Outcome, clip(scrubURLs(c.Error)), c.CCVersion, c.Version) return err } @@ -186,16 +213,16 @@ func (s *Store) RecordCall(ctx context.Context, c ToolCall) error { func (s *Store) RecordAttempt(ctx context.Context, a Attempt) error { a.URL, a.Host = NormalizeURL(a.URL) _, err := s.db.ExecContext(ctx, ` - INSERT INTO attempts (ts, fetch_id, via, url, host, client, outcome, status, bytes, ms, error) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ms(a.Time), a.FetchID, a.Via, a.URL, a.Host, a.Client, a.Outcome, a.Status, a.Bytes, a.Duration.Milliseconds(), clip(scrubURLs(a.Error))) + INSERT INTO attempts (ts, fetch_id, via, url, host, client, outcome, status, bytes, ms, error, version) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ms(a.Time), a.FetchID, a.Via, a.URL, a.Host, a.Client, a.Outcome, a.Status, a.Bytes, a.Duration.Milliseconds(), clip(scrubURLs(a.Error)), a.Version) return err } // Calls returns the tool calls since t, oldest first. func (s *Store) Calls(ctx context.Context, since time.Time) ([]ToolCall, error) { rows, err := s.db.QueryContext(ctx, ` - SELECT ts, session_id, tool_use_id, tool, url, host, outcome, error, cc_version + SELECT ts, session_id, tool_use_id, tool, url, host, outcome, error, cc_version, version FROM tool_calls WHERE ts >= ? ORDER BY ts, id`, since.UnixMilli()) if err != nil { return nil, err @@ -205,7 +232,7 @@ func (s *Store) Calls(ctx context.Context, since time.Time) ([]ToolCall, error) for rows.Next() { var c ToolCall var ts int64 - if err := rows.Scan(&ts, &c.SessionID, &c.ToolUseID, &c.Tool, &c.URL, &c.Host, &c.Outcome, &c.Error, &c.CCVersion); err != nil { + if err := rows.Scan(&ts, &c.SessionID, &c.ToolUseID, &c.Tool, &c.URL, &c.Host, &c.Outcome, &c.Error, &c.CCVersion, &c.Version); err != nil { return nil, err } c.Time = time.UnixMilli(ts) @@ -217,7 +244,7 @@ func (s *Store) Calls(ctx context.Context, since time.Time) ([]ToolCall, error) // Attempts returns the attempts since t, oldest first. func (s *Store) Attempts(ctx context.Context, since time.Time) ([]Attempt, error) { rows, err := s.db.QueryContext(ctx, ` - SELECT ts, fetch_id, via, url, host, client, outcome, status, bytes, ms, error + SELECT ts, fetch_id, via, url, host, client, outcome, status, bytes, ms, error, version FROM attempts WHERE ts >= ? ORDER BY ts, id`, since.UnixMilli()) if err != nil { return nil, err @@ -227,7 +254,7 @@ func (s *Store) Attempts(ctx context.Context, since time.Time) ([]Attempt, error for rows.Next() { var a Attempt var ts, dur int64 - if err := rows.Scan(&ts, &a.FetchID, &a.Via, &a.URL, &a.Host, &a.Client, &a.Outcome, &a.Status, &a.Bytes, &dur, &a.Error); err != nil { + if err := rows.Scan(&ts, &a.FetchID, &a.Via, &a.URL, &a.Host, &a.Client, &a.Outcome, &a.Status, &a.Bytes, &dur, &a.Error, &a.Version); err != nil { return nil, err } a.Time, a.Duration = time.UnixMilli(ts), time.Duration(dur)*time.Millisecond diff --git a/store/store_test.go b/store/store_test.go index b2b6328..8e6eee4 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -182,3 +182,59 @@ func TestNeedsRender(t *testing.T) { } } } + +func TestUpgradeAddsVersions(t *testing.T) { + path := filepath.Join(t.TempDir(), "events.db") + old := strings.NewReplacer(",\n\tversion TEXT NOT NULL DEFAULT ''", "", ",\n\tversion TEXT NOT NULL DEFAULT ''", "", + "user_version = 2", "user_version = 1").Replace(schema) + if strings.Contains(old, "\tversion ") || !strings.Contains(old, "user_version = 1") { + t.Fatal("could not derive the version 1 schema") + } + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + if _, err := s.db.ExecContext(t.Context(), "DROP TABLE tool_calls; DROP TABLE attempts; DROP TABLE daily;"+old); err != nil { + t.Fatal(err) + } + _ = s.Close() + + var wg sync.WaitGroup // several hooks and servers open the old file at once + errs := make(chan error, 4) + for range 4 { + wg.Go(func() { + s, err := Open(t.Context(), path) + if err == nil { + err = s.Close() + } + errs <- err + }) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + s, err = Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + now := time.Now() + if err := s.RecordAttempt(t.Context(), Attempt{Time: now, FetchID: "f", Via: "mcp", URL: "https://a.example/", Client: "chrome_like", Outcome: "ok", Version: "0.6.0"}); err != nil { + t.Fatal(err) + } + if err := s.RecordCall(t.Context(), ToolCall{Time: now, ToolUseID: "u", Tool: "WebFetch", URL: "https://a.example/", Outcome: "ok", Version: "0.6.0"}); err != nil { + t.Fatal(err) + } + as, err := s.Attempts(t.Context(), time.Time{}) + if err != nil || len(as) != 1 || as[0].Version != "0.6.0" { + t.Errorf("attempts after the upgrade: %+v, %v", as, err) + } + cs, err := s.Calls(t.Context(), time.Time{}) + if err != nil || len(cs) != 1 || cs[0].Version != "0.6.0" { + t.Errorf("calls after the upgrade: %+v, %v", cs, err) + } +}