The port replaced its last diesel crane this week.
", 6)
+ walls := []struct{ name, url, contentType, body, want string }{
+ {"paywalled article", pageURL, "text/html", paid + teaser, paywallNote},
+ {"rendered gate", pageURL, "text/html", teaser + "Thank you for your patience while we verify access.
", paywallNote},
+ {"soft 404 first", pageURL, "text/html", paid + soft404, goneNote},
+ {"login form first", pageURL, "text/html", paid + facebookLogin, loginNote},
+ {"before the thin note", pageURL, "text/html", paid + "Cranes.
", paywallNote},
+ {"before the social note", "https://x.com/NASA", "text/html", paid + profile, paywallNote},
+ {"markdown from a site route", pageURL, fetch.TypeMarkdown, paid + "\n\nSubscribe to continue reading. " + strings.Repeat("Cranes. ", 40), ""},
+ }
+ for _, c := range walls {
+ p := fetch.Page{Body: []byte(c.body), ContentType: c.contentType, URL: c.url}
+ if got := pageNote(p, c.url, pageText(p, c.url, "", false)); got != c.want {
+ t.Errorf("%s: pageNote = %q, want %q", c.name, got, c.want)
+ }
+ }
+
fp := &fakePages{page: okPage(soft404)}
usePages(t, fp)
out, err := fetchPage(t.Context(), newFetcherWith(config.Default(), nil, "mcp", nil), t.TempDir(), fetchInput{URL: pageURL})
diff --git a/config/config.go b/config/config.go
index 7701bc2..95f46b7 100644
--- a/config/config.go
+++ b/config/config.go
@@ -28,6 +28,7 @@ type Config struct {
Mode string `toml:"mode"` // nudge or inline (hook response)
UserAgent string `toml:"user_agent"` // the plain client's User-Agent; empty = refetch/
UseProxy bool `toml:"use_proxy"` // connect through HTTPS_PROXY; a TLS-decrypting one replaces the Chrome handshake
+ Archive string `toml:"archive"` // wayback or off: look a page that cannot be read up at archive.org
}
// Duration is a time.Duration written as "10s" in TOML and env vars.
@@ -55,6 +56,7 @@ func Default() Config {
Timeout: Duration{20 * time.Second},
Stats: true,
Mode: "nudge",
+ Archive: "wayback",
}
}
@@ -110,6 +112,7 @@ func (c *Config) applyEnv(getenv func(string) string) error {
"REFETCH_RENDER": &c.Render,
"REFETCH_MODE": &c.Mode,
"REFETCH_USER_AGENT": &c.UserAgent,
+ "REFETCH_ARCHIVE": &c.Archive,
}
for k, p := range strs {
if v := getenv(k); v != "" {
@@ -149,6 +152,7 @@ func (c Config) Validate() error {
check("impersonate", c.Impersonate, "always", "fallback", "off")
check("render", c.Render, "auto", "off")
check("mode", c.Mode, "nudge", "inline")
+ check("archive", c.Archive, "wayback", "off")
if c.Timeout.Duration <= 0 || c.RenderTimeout.Duration <= 0 {
errs = append(errs, errors.New("timeout and render_timeout must be positive"))
}
diff --git a/config/config_test.go b/config/config_test.go
index 87eff4b..1fb703d 100644
--- a/config/config_test.go
+++ b/config/config_test.go
@@ -17,7 +17,7 @@ func TestDefaultsWithoutFile(t *testing.T) {
if c != Default() {
t.Errorf("got %+v", c)
}
- if c.Impersonate != "always" || c.Render != "auto" || !c.Stats || c.RespectRobots || c.Mode != "nudge" {
+ if c.Impersonate != "always" || c.Render != "auto" || !c.Stats || c.RespectRobots || c.Mode != "nudge" || c.Archive != "wayback" {
t.Errorf("defaults changed: %+v", c)
}
}
@@ -46,6 +46,7 @@ func TestInvalid(t *testing.T) {
"bad mode": "mode = \"loud\"\n",
"unknown key": "impersonat = \"off\"\n",
"bad dur": "timeout = \"soon\"\n",
+ "bad archive": "archive = \"archive.today\"\n",
} {
path := filepath.Join(dir, strings.ReplaceAll(name, " ", "_")+".toml")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
@@ -100,3 +101,23 @@ func TestUseProxyFromEnv(t *testing.T) {
t.Errorf("REFETCH_USE_PROXY=true: %v", err)
}
}
+
+func TestArchive(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "config.toml")
+ if err := os.WriteFile(path, []byte("archive = \"off\"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("REFETCH_CONFIG", path)
+ t.Setenv("REFETCH_ARCHIVE", "")
+ if c, err := Load(); err != nil || c.Archive != "off" {
+ t.Errorf("archive = \"off\" in the file: %+v, %v", c, err)
+ }
+ t.Setenv("REFETCH_ARCHIVE", "wayback")
+ if c, err := Load(); err != nil || c.Archive != "wayback" {
+ t.Errorf("REFETCH_ARCHIVE=wayback over the file: %+v, %v", c, err)
+ }
+ t.Setenv("REFETCH_ARCHIVE", "on")
+ if _, err := Load(); err == nil || !strings.Contains(err.Error(), "archive") {
+ t.Errorf("REFETCH_ARCHIVE=on accepted: %v", err)
+ }
+}
diff --git a/e2e/run.py b/e2e/run.py
index 5fd6a00..d5554ef 100644
--- a/e2e/run.py
+++ b/e2e/run.py
@@ -108,7 +108,7 @@ def main():
if data.exists():
shutil.rmtree(data)
env = {**os.environ, "REFETCH_BIN": str(build / "refetch-e2e"), "REFETCH_DATA": str(data),
- "REFETCH_CONFIG": str(out / "none.toml"), "NODE_EXTRA_CA_CERTS": str(ca)}
+ "REFETCH_CONFIG": str(out / "none.toml"), "REFETCH_ARCHIVE": "off", "NODE_EXTRA_CA_CERTS": str(ca)}
if setup == "no-chrome":
env["REFETCH_CHROME"] = str(out / "no-chrome")
cfg = settings(setup, out)
diff --git a/fetch/detect.go b/fetch/detect.go
index 7aae1cb..e72a74d 100644
--- a/fetch/detect.go
+++ b/fetch/detect.go
@@ -4,6 +4,7 @@ import (
"bytes"
"net/http"
"regexp"
+ "slices"
"strings"
)
@@ -15,9 +16,13 @@ var challengeMarkers = []string{
"prove your humanity",
}
+const maxChallengeText = 2000
+
// Challenge reports whether a response is a bot challenge rather than the
// page: HTTP 503, HTTP 202 (AWS WAF answers a GET with an empty 202 and a
-// challenge script), or a short page carrying a challenge marker.
+// challenge script), or a page with little text carrying a challenge
+// marker: bot managers inject their scripts into real pages too (The
+// Atlantic's articles load /cdn-cgi/challenge-platform/scripts/).
func Challenge(status int, body []byte) bool {
if status == http.StatusServiceUnavailable || status == http.StatusAccepted {
return true
@@ -26,12 +31,10 @@ func Challenge(status int, body []byte) bool {
return false
}
lower := strings.ToLower(string(body))
- for _, m := range challengeMarkers {
- if strings.Contains(lower, m) {
- return true
- }
+ if !slices.ContainsFunc(challengeMarkers, func(m string) bool { return strings.Contains(lower, m) }) {
+ return false
}
- return false
+ return len([]rune(Text(body, "text/html"))) < maxChallengeText
}
var mountPoint = regexp.MustCompile(`(?i)]+id=["']?(root|app|__next|__nuxt|svelte|main)["']?[^>]*>\s*
|]*>\s*`)
diff --git a/fetch/detect_test.go b/fetch/detect_test.go
index 84c0436..d360972 100644
--- a/fetch/detect_test.go
+++ b/fetch/detect_test.go
@@ -3,6 +3,7 @@ package fetch
import (
"os"
"path/filepath"
+ "strings"
"testing"
)
@@ -34,6 +35,13 @@ func TestDetectFixtures(t *testing.T) {
if !Challenge(202, nil) {
t.Error("an empty 202 to a GET is a challenge")
}
+ article := []byte(`Is Google Making Us Stupid?` +
+ strings.Repeat("Over the past few years I've had an uncomfortable sense that someone has been tinkering with my brain. ", 30) +
+ `
`)
+ if Challenge(200, article) {
+ t.Error("an article with a bot manager's injected script is a challenge")
+ }
rendered := []byte(`Secret word: elder
Rendered after load.
`)
if EmptyRendered(rendered) || !EmptyRendered([]byte(``)) {
t.Error("EmptyRendered misclassifies")
diff --git a/fetch/paywall.go b/fetch/paywall.go
new file mode 100644
index 0000000..95e448a
--- /dev/null
+++ b/fetch/paywall.go
@@ -0,0 +1,110 @@
+package fetch
+
+import (
+ "bytes"
+ "regexp"
+ "slices"
+ "strings"
+
+ "golang.org/x/net/html"
+)
+
+// paywallChars is the most text a page cut at its paywall gives; a longer
+// text with a gate's words has them in its header or footer. The New York
+// Times' cut article reads about 4,400 characters.
+const paywallChars = 6000
+
+var (
+ // paywallGate is a sentence only a paywall says.
+ paywallGate = regexp.MustCompile(`while we (?:verify|are verifying|check|are checking) (?:your )?access|` +
+ `subscribe (?:now )?to (?:continue|keep) reading|subscribe to read (?:the full|the rest|more)|` +
+ `to (?:continue|keep) reading,? (?:please )?(?:subscribe|become a subscriber)|` +
+ `(?:this|the) (?:article|story) is (?:only )?(?:available )?(?:for|to) (?:paying )?subscribers|` +
+ `subscribers?[- ]only (?:article|story|content)`)
+ alreadySubscribed = regexp.MustCompile(`already (?:a subscriber|subscribed)\?`)
+ subscribePrompt = regexp.MustCompile(`(?:subscribe|subscription) (?:now |today )?(?:to read|to continue|to unlock|for (?:full|unlimited))|` +
+ `become a subscriber|want all of`)
+)
+
+// Paywall reports an HTML page whose article is for subscribers: its
+// schema.org data marks the article not free, or the page gives under
+// paywallChars of text (textChars, as read) and shows a paywall. A page
+// marked not free can still give the whole article.
+func Paywall(body []byte, contentType string, textChars int) bool {
+ if !isHTML(body, contentType) {
+ return false
+ }
+ doc, err := html.Parse(bytes.NewReader(body))
+ if err != nil {
+ return false
+ }
+ for v := range jsonLD(doc) {
+ if notFree(v, 0) {
+ return true
+ }
+ }
+ if textChars >= paywallChars {
+ return false
+ }
+ var b strings.Builder
+ shownText(doc, &b)
+ shown := strings.ToLower(strings.ReplaceAll(oneLineText(b.String()), "’", "'"))
+ return paywallGate.MatchString(shown) || alreadySubscribed.MatchString(shown) && subscribePrompt.MatchString(shown)
+}
+
+// notFree reports a schema.org article that isAccessibleForFree marks
+// false, itself or a part of it (hasPart), as publishers mark paywalled
+// text for search engines.
+func notFree(v any, depth int) bool {
+ if depth > maxLDDepth {
+ return false
+ }
+ switch t := v.(type) {
+ case []any:
+ return slices.ContainsFunc(t, func(e any) bool { return notFree(e, depth+1) })
+ case map[string]any:
+ if hasType(t, isArticle) && (falseFlag(t["isAccessibleForFree"]) || partNotFree(t["hasPart"])) {
+ return true
+ }
+ return notFree(t["@graph"], depth+1) || notFree(t["mainEntity"], depth+1)
+ }
+ return false
+}
+
+func isArticle(t string) bool {
+ return strings.HasSuffix(strings.ToLower(t), "article") ||
+ containsFold([]string{"BlogPosting", "LiveBlogPosting", "Report", "WebPage", "CreativeWork"}, t)
+}
+
+func partNotFree(v any) bool {
+ switch t := v.(type) {
+ case map[string]any:
+ return falseFlag(t["isAccessibleForFree"])
+ case []any:
+ return slices.ContainsFunc(t, func(e any) bool {
+ m, ok := e.(map[string]any)
+ return ok && falseFlag(m["isAccessibleForFree"])
+ })
+ }
+ return false
+}
+
+// falseFlag is a JSON-LD false: sites write the boolean or the string.
+func falseFlag(v any) bool {
+ b, ok := v.(bool)
+ return ok && !b || strings.EqualFold(strings.TrimSpace(str(v)), "false")
+}
+
+// shownText writes the text of n's shown elements, a space after each
+// text node, so that the words of adjacent blocks stay apart.
+func shownText(n *html.Node, b *strings.Builder) {
+ for c := range n.ChildNodes() {
+ switch {
+ case c.Type == html.TextNode:
+ b.WriteString(c.Data)
+ b.WriteByte(' ')
+ case c.Type == html.ElementNode && !hidden(c) && !skipped(c):
+ shownText(c, b)
+ }
+ }
+}
diff --git a/fetch/paywall_test.go b/fetch/paywall_test.go
new file mode 100644
index 0000000..0c3e5d8
--- /dev/null
+++ b/fetch/paywall_test.go
@@ -0,0 +1,57 @@
+package fetch
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf8"
+)
+
+func TestPaywall(t *testing.T) {
+ ld := func(data string) string { return `` }
+ teaser := "Harbour cranes go electric
The port replaced its last diesel crane this week.
" +
+ "Officials said the switch cuts noise at night.
"
+ article := "Harbour cranes go electric
" +
+ strings.Repeat("The port replaced its last diesel crane this week, and officials said the switch cuts noise at night.
", 80) + ""
+ gate := `Thank you for your patience while we verify access.
+
Already a subscriber? Log in.
Want all of The Daily? Subscribe.
`
+ cases := []struct {
+ name, contentType, body string
+ want bool
+ }{
+ {"flat false", "text/html", ld(`{"@context":"https://schema.org","@type":"NewsArticle","headline":"H","isAccessibleForFree":false}`) + teaser, true},
+ {"graph, string False", "text/html", ld(`{"@graph":[{"@type":"WebSite","name":"Daily"},{"@type":["ReportageNewsArticle"],"isAccessibleForFree":"False"}]}`) + teaser, true},
+ {"top-level list", "text/html", ld(`[{"@type":"BreadcrumbList"},{"@type":"Article","isAccessibleForFree":"false"}]`) + teaser, true},
+ {"hasPart", "text/html", ld(`{"@type":"NewsArticle","hasPart":{"@type":"WebPageElement","isAccessibleForFree":false,"cssSelector":".paywall"}}`) + teaser, true},
+ {"hasPart list", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":"False","hasPart":[{"@type":"WebPageElement","isAccessibleForFree":"False","cssSelector":"[data-lock]"}]}`) + teaser, true},
+ {"page's main entity", "text/html", ld(`{"@type":"WebPage","mainEntity":{"@type":"BlogPosting","isAccessibleForFree":false}}`) + teaser, true},
+ {"marked but long", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":false}`) + article, true},
+ {"free", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":true}`) + teaser, false},
+ {"free as a string", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":"True"}`) + teaser, false},
+ {"free part", "text/html", ld(`{"@type":"NewsArticle","hasPart":{"@type":"WebPageElement","isAccessibleForFree":true}}`) + teaser, false},
+ {"false off the article", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":true,"isPartOf":{"@type":["CreativeWork","Product"],"isAccessibleForFree":false}}`) + teaser, false},
+ {"false on a product", "text/html", ld(`{"@type":"Product","isAccessibleForFree":false}`) + teaser, false},
+ {"broken JSON-LD", "text/html", ld(`{"@type":"NewsArticle","isAccessibleForFree":false`) + teaser, false},
+ {"no JSON-LD", "text/html", teaser, false},
+ {"rendered gate", "text/html", teaser + gate, true},
+ {"continue reading", "text/html", teaser + `To continue reading, please subscribe.
`, true},
+ {"subscribers' story", "text/html", teaser + `This article is only available to subscribers.
`, true},
+ {"sign-in prompt and offer", "text/html", teaser + `Already a subscriber? Sign in
Subscribe now for full access.
`, true},
+ {"sign-in prompt alone", "text/html", teaser + `Already a subscriber? Sign in
`, false},
+ {"full article, header sign-in", "text/html", `` + article, false},
+ {"hidden gate", "text/html", teaser + `Subscribe to continue reading.
` +
+ `Thank you for your patience while we verify access.
` +
+ `This story is for subscribers.
`, false},
+ {"access docs", "text/html", "Bucket policies
Run the check to verify access to the bucket before checking your access keys.
", false},
+ {"members' page", "text/html", teaser + "This story is for members of the press.
", false},
+ {"gate words in a script", "text/html", teaser + ``, false},
+ {"footer link", "text/html", teaser + ``, false},
+ {"markdown", TypeMarkdown, "# Harbour cranes\n\nSubscribe to continue reading.\n\n" + ld(`{"@type":"NewsArticle","isAccessibleForFree":false}`), false},
+ {"plain text", "text/plain", "Subscribe to continue reading.", false},
+ }
+ for _, c := range cases {
+ chars := utf8.RuneCountInString(Markdown([]byte(c.body), c.contentType, nil))
+ if got := Paywall([]byte(c.body), c.contentType, chars); got != c.want {
+ t.Errorf("%s: Paywall = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
diff --git a/fetch/structured.go b/fetch/structured.go
index c670ceb..7bb278d 100644
--- a/fetch/structured.go
+++ b/fetch/structured.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json/v2"
"fmt"
+ "iter"
"net/url"
"strings"
@@ -30,13 +31,8 @@ func Structured(body []byte, page *url.URL) string {
func structured(doc *html.Node, page *url.URL) string {
s := &ldWriter{page: page}
- for n := range doc.Descendants() {
- if n.Type == html.ElementNode && n.DataAtom == atom.Script && strings.EqualFold(attr(n, "type"), "application/ld+json") && n.FirstChild != nil {
- var v any
- if json.Unmarshal([]byte(n.FirstChild.Data), &v) == nil {
- s.walk(v, 0)
- }
- }
+ for v := range jsonLD(doc) {
+ s.walk(v, 0)
}
if s.text < minTrimmed {
return ""
@@ -44,6 +40,21 @@ func structured(doc *html.Node, page *url.URL) string {
return StructuredLabel + "\n\n" + strings.TrimSpace(s.b.String())
}
+// jsonLD yields the value of each JSON-LD script of a parsed page that
+// parses.
+func jsonLD(doc *html.Node) iter.Seq[any] {
+ return func(yield func(any) bool) {
+ for n := range doc.Descendants() {
+ if n.Type == html.ElementNode && n.DataAtom == atom.Script && strings.EqualFold(attr(n, "type"), "application/ld+json") && n.FirstChild != nil {
+ var v any
+ if json.Unmarshal([]byte(n.FirstChild.Data), &v) == nil && !yield(v) {
+ return
+ }
+ }
+ }
+ }
+}
+
// ldWriter writes the posts it finds; text counts their characters.
type ldWriter struct {
b strings.Builder
@@ -148,12 +159,18 @@ func (s *ldWriter) markdown(t string) string {
}
func isType(n map[string]any, types ...string) bool {
+ return hasType(n, func(t string) bool { return containsFold(types, t) })
+}
+
+// hasType reports a node with an @type, one or one of a list, that match
+// accepts.
+func hasType(n map[string]any, match func(string) bool) bool {
switch t := n["@type"].(type) {
case string:
- return containsFold(types, t)
+ return match(t)
case []any:
for _, e := range t {
- if s, ok := e.(string); ok && containsFold(types, s) {
+ if s, ok := e.(string); ok && match(s) {
return true
}
}
diff --git a/site/bloomberg.go b/site/bloomberg.go
new file mode 100644
index 0000000..e1fa8f0
--- /dev/null
+++ b/site/bloomberg.go
@@ -0,0 +1,354 @@
+package site
+
+import (
+ "bytes"
+ "context"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
+ "fmt"
+ "maps"
+ "net/url"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+ "unicode"
+)
+
+var nextData = regexp.MustCompile(`