Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ fetcher and the stats report. The repo root is also the Claude Code plugin.
under `render_timeout`
- `site/`: a site's own public API in place of its page: Stack Exchange
questions, Discourse topics (`/raw`), long GitHub issues, Bluesky and
Mastodon posts, YouTube video data, Medium posts from RSS feeds
Mastodon posts, YouTube video data, Medium posts from RSS feeds,
Bloomberg story data
- `cmd/refetch/archive.go`: the Wayback Machine step after a failed read
(`archive` setting); it sends the URL to archive.org
- `store/`: SQLite event log (`tool_calls`, `attempts`, `daily` roll-up)
- `stats/`: the funnel and its text report
- `config/`: defaults, `config.toml`, `REFETCH_*` env vars
Expand Down
38 changes: 31 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ Chrome step, which adds JavaScript-only pages and some challenges.
many refetch picked up and which step resolved them. All data stays on
your machine.
- **Safe by default.** Public addresses only, one page per call, no
crawling, no cookies kept.
crawling, no cookies kept. A URL refetch cannot read is looked up at the
Wayback Machine unless you turn that off.

## Install

Expand Down Expand Up @@ -121,8 +122,10 @@ flowchart TD
Client -- "challenge or<br/>JavaScript-only page" --> Headless["2. Headless Chrome<br/>your installed Chrome, 15 s at most"]
Client -- "page" --> Text["Page as Markdown"]
Headless -- "page" --> Text
Client -- "HTTP 403/429<br/>or error" --> Handoff["Hand-off: why it failed"]
Headless -- "still blocked" --> Handoff
Client -- "HTTP 403/429<br/>or error" --> Wayback["3. Wayback Machine<br/>latest archived copy, 20 s at most"]
Headless -- "still blocked" --> Wayback
Wayback -- "snapshot" --> Text
Wayback -- "none" --> Handoff["Hand-off: why it failed"]
end

Text --> Rescued(["Claude answers from the page"])
Expand Down Expand Up @@ -160,8 +163,13 @@ show how often each path was taken. Step by step:
without Chrome. A host whose last two fetches in the past week only
headless Chrome could read goes straight to it (this needs `stats` on, as
it reads the stats database); the HTTP clients still run if it fails.
5. If both steps fail, the result says why and suggests a browser tool if
you have one.
5. If both steps fail (a refusal, a challenge, an error page, a dead host),
refetch looks the URL up at the Wayback Machine and reads its latest
snapshot saved with HTTP 200, within 20 s. The result says it is an
archived copy, gives its date and why the live page failed, and warns that
it may be out of date. `archive = "off"` turns this step off.
6. If there is no snapshot either, the result says why and suggests a
browser tool if you have one.

`fetch_page` returns a page as Markdown: headings, lists, links, tables and
code blocks kept, scripts and hidden elements dropped. So is the site's own
Expand Down Expand Up @@ -212,6 +220,11 @@ Some sites serve the same public content better through their own API, and
pages challenge automated readers. The feed holds the full text of only
the newest posts, about ten; for an older or member-only post, or a
`medium.com/p/…` address, refetch reads the page as before.
- Bloomberg articles are read from the story data their page carries for
its scripts. The HTML around it shows only the byline and the first
paragraphs; the data holds the whole text a reader without cookies is
served, rendered with its headline, authors, date, takeaways, headings,
lists and links. No extra request is made.

When a site's API says refetch has used up its quota (HTTP 429, a Stack
Exchange throttle or GitHub's rate-limit message), refetch leaves that API
Expand All @@ -224,8 +237,11 @@ When a page loads but is not the content, the result starts with a note: a
short page that is mostly a login form, a page whose title or main heading
says it does not exist (a "soft 404" sent with HTTP 200), or the signed-out
view of X, Instagram, Facebook, Threads, TikTok and LinkedIn, which may lack
the posts, comments and full profiles that need a signed-in browser. The
page text still comes back.
the posts, comments and full profiles that need a signed-in browser. A news
article whose schema.org data marks it for subscribers, or whose page shows
a paywall ("Subscribe to continue reading"), gets a note that the text may
stop at the paywall and be only the opening. The page text still comes back,
and notes change no outcome or statistic.

Pages that put their content in `<noscript>` (Discourse lists) or keep it
hidden until a script shows it (Zendesk help articles) are read from there
Expand Down Expand Up @@ -283,6 +299,7 @@ another file. Everything is on by default.
| `mode` | `REFETCH_MODE` | `"nudge"` | `"inline"`: the hook fetches the page itself and puts its first 8,000 characters next to the failed result |
| `user_agent` | `REFETCH_USER_AGENT` | `refetch/<version>` | The plain client's User-Agent |
| `use_proxy` | `REFETCH_USE_PROXY` | `false` | `true` sends connections through `HTTPS_PROXY`, except to hosts `NO_PROXY` lists. Off by default because a proxy that decrypts TLS replaces the Chrome-like handshake with its own |
| `archive` | `REFETCH_ARCHIVE` | `"wayback"` | `"wayback"`: when a page cannot be read, look its URL up at the Wayback Machine (archive.org) and read the latest archived copy. `"off"`: never send failed URLs to archive.org |

```toml
# ~/.config/refetch/config.toml
Expand Down Expand Up @@ -323,6 +340,13 @@ These limits are always on, whatever the settings:
- No cookies are kept between calls: each render uses a throwaway Chrome
profile.
- Pages are capped at 2 MB, and PDF and office files at 32 MB.
- Only failed reads go to archive.org: when refetch cannot read a page (in
`fetch_page`, or in the hook with `mode = "inline"`), it sends that URL to
archive.org to look for an archived copy, unless `archive = "off"`. It never
does this for pages it read, private addresses, pages robots.txt disallows
(with `respect_robots`), Google Docs and Drive links, or URLs with a user
name or a credential-like query parameter (`token`, `key`, `sig`, `code`,
`X-Amz-*`, …).
- refetch drives headless Chrome over a pipe, not a debugging port, so no
other program on the machine can reach it.

Expand Down
174 changes: 174 additions & 0 deletions cmd/refetch/archive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package main

import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
neturl "net/url"
"slices"
"strings"
"time"

"github.com/samgozman/refetch/fetch"
"github.com/samgozman/refetch/store"
)

// The Wayback Machine step: when every live step failed, the latest
// snapshot archive.org kept with HTTP 200, read as the site served it.
const (
archiveClient = "wayback"
outcomeNoSnapshot = "no_snapshot"
archiveHost = "web.archive.org"
// archiveBudget caps the lookup and the snapshot together; a Get alone
// can take two client timeouts.
archiveBudget = 20 * time.Second
// fastLatest keeps limit=-1 (the newest row) quick for URLs with many
// captures.
cdxQuery = "https://web.archive.org/cdx/search/cdx?output=json&limit=-1&fastLatest=true&filter=statuscode:200&fl=timestamp,original&url="
cdxTimeFmt = "20060102150405"
archiveDate = "2 Jan 2006"
)

var errNoSnapshot = errors.New("no snapshot")

// secretKeys are query keys that may carry a credential; a URL with one is
// never sent to archive.org. Matched whole, or as a part of the key for
// the longer words.
var (
secretKeys = []string{"key", "sig", "code", "auth", "sid", "pwd", "jwt", "otp"}
secretParts = []string{"token", "secret", "password", "passwd", "signature", "session", "sessid", "apikey", "api_key", "credential"}
secretPrefixes = []string{"x-amz-", "x-goog-"}
)

// mayCarrySecret reports whether rawURL has userinfo or a credential-like
// query key, or a query refetch cannot parse to tell.
func mayCarrySecret(rawURL string) bool {
u, err := neturl.Parse(rawURL)
if err != nil || u.User != nil {
return true
}
q, err := neturl.ParseQuery(u.RawQuery)
if err != nil {
return true
}
for k := range q {
k = strings.ToLower(k)
has := func(s string) bool { return strings.Contains(k, s) }
prefixed := func(s string) bool { return strings.HasPrefix(k, s) }
if slices.Contains(secretKeys, k) || slices.ContainsFunc(secretParts, has) || slices.ContainsFunc(secretPrefixes, prefixed) {
return true
}
}
return false
}

// archiveWorthy reports whether a failed read goes on to the Wayback
// Machine: not for a page the site or the settings would not let refetch
// read, a file that is not text, or a URL that may carry a secret.
func (fr *fetcher) archiveWorthy(ctx context.Context, url string, p fetch.Page, err error) bool {
disallowed := func(a fetch.Attempt) bool { return a.Outcome == fetch.OutcomeDisallowed }
switch {
case !fr.archive, err == nil, len(p.Attempts) == 0, ctx.Err() != nil,
slices.ContainsFunc(p.Attempts, disallowed),
errors.Is(err, fetch.ErrNotText), errors.Is(err, fetch.ErrDocument),
strings.Contains(err.Error(), "not a public address"),
fr.cooling(archiveHost):
return false
}
_, host := store.NormalizeURL(url)
return !slices.Contains(noArchiveHosts, host) && !mayCarrySecret(url)
}

// noArchiveHosts are never looked up: archive.org itself, and Google Docs
// and Drive, whose document links work as their passwords.
var noArchiveHosts = []string{archiveHost, "archive.org", "docs.google.com", "drive.google.com"}

// viaArchive reads url's latest Wayback Machine snapshot, as one attempt
// after p's. On failure p and the live error come back with the attempt
// added, so the hand-off still explains the live failure.
func (fr *fetcher) viaArchive(ctx context.Context, url string, p fetch.Page, liveErr error) (fetch.Page, error) {
ctx, cancel := context.WithTimeout(ctx, archiveBudget)
defer cancel()
target := url
if u, err := neturl.Parse(url); err == nil {
u.Fragment, u.RawFragment = "", ""
target = u.String()
}
_, host := store.NormalizeURL(url)
a := fetch.Attempt{URL: url, Host: host, Client: archiveClient}
start := time.Now()
got, ts, err := fr.snapshot(ctx, target)
a.Duration, a.Status, a.Bytes = time.Since(start), got.Last.Status, len(got.Body)
if err != nil {
a.Outcome, a.Err = archiveOutcome(got, err), "Wayback Machine: "+err.Error()
p.Attempts = append(p.Attempts, a)
return p, liveErr
}
a.Outcome = fetch.OutcomeOK
via := fmt.Sprintf("Wayback Machine's copy of %s (https://%s/web/%s/%s), not the live page, which failed: %s",
ts.Format(archiveDate), archiveHost, ts.Format(cdxTimeFmt), target, oneLine(liveErr.Error(), 200))
// Links resolve against the page's own address, not web.archive.org's.
return fetch.Page{Body: got.Body, ContentType: got.ContentType, URL: target, Last: a, Attempts: append(p.Attempts, a), Via: via}, nil
}

// archiveOutcome names a failed Wayback Machine step.
func archiveOutcome(got fetch.Page, err error) string {
switch o := got.Last.Outcome; {
case errors.Is(err, errNoSnapshot):
return outcomeNoSnapshot
case isTimeoutErr(err):
return fetch.OutcomeTimeout
case o != "" && o != fetch.OutcomeOK:
return o
}
return fetch.OutcomeError
}

// snapshot looks up url's latest snapshot with HTTP 200 and reads it raw
// (id_): no Wayback toolbar, links as the site wrote them.
func (fr *fetcher) snapshot(ctx context.Context, url string) (fetch.Page, time.Time, error) {
got, err := fr.f.Get(ctx, cdxQuery+neturl.QueryEscape(url))
if err != nil {
if got.Last.Status == http.StatusTooManyRequests {
fr.coolDown(archiveHost)
}
return got, time.Time{}, fmt.Errorf("lookup: %w", err)
}
var rows [][]string
if json.Unmarshal(got.Body, &rows) != nil || len(rows) < 2 || len(rows[len(rows)-1]) == 0 {
return fetch.Page{}, time.Time{}, errNoSnapshot
}
ts, err := time.Parse(cdxTimeFmt, rows[len(rows)-1][0])
if err != nil {
return fetch.Page{}, time.Time{}, errNoSnapshot
}
got, err = fr.f.Get(ctx, fmt.Sprintf("https://%s/web/%sid_/%s", archiveHost, ts.Format(cdxTimeFmt), url))
if err != nil {
if got.Last.Status == http.StatusTooManyRequests {
fr.coolDown(archiveHost)
}
return got, ts, err
}
if strings.Contains(got.ContentType, "html") {
switch {
case fetch.Challenge(http.StatusOK, got.Body):
got.Last.Outcome = fetch.OutcomeChallenge
return got, ts, errors.New("the snapshot is a challenge page")
case fetch.NeedsJS(got.Body, got.ContentType):
got.Last.Outcome = fetch.OutcomeNeedsJS
return got, ts, errors.New("the snapshot is a JavaScript-only page")
}
}
return got, ts, nil
}

// archiveNote is the head line of a page read from the Wayback Machine:
// an archived copy, its date, and why the live page failed.
func archiveNote(p fetch.Page) string {
if p.Last.Client != archiveClient {
return ""
}
return "Read from the " + p.Via + ". It may be out of date."
}
Loading