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
90 changes: 90 additions & 0 deletions .flox/env/manifest.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .flox/env/manifest.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ sqlite-interactive.pkg-path = "sqlite-interactive"
sqlite-interactive.outputs = "all"
gum.pkg-path = "gum"
flyctl.pkg-path = "flyctl"
wrangler.pkg-path = "wrangler"


## Environment Variables ---------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ bin/*
*-shm
*-wal
.env
.wrangler/
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ present** — useful for container platforms.
|----------|-------------|---------|
| `TUMBLE_ADMIN_SECRET` | Secret for admin API operations | |
| `TUMBLE_CLICK_SIGNING_KEY` | Secret for signed click tracking | |
| `TUMBLE_UNFURL_WORKER_URL` | Cloudflare Worker that fetches pages which challenge the server (see `cloudflare/unfurl/`) | |
| `TUMBLE_UNFURL_WORKER_KEY` | Shared secret for the unfurl worker | |

**Site & RSS feed metadata**

Expand Down Expand Up @@ -358,6 +360,21 @@ fly secrets set TUMBLE_ADMIN_SECRET="$(openssl rand -hex 32)"
fly secrets set TUMBLE_CLICK_SIGNING_KEY="$(openssl rand -hex 32)" # optional
```

**Optional: unfurl worker.** Some sites behind Cloudflare challenge
requests from hosting providers, so previews for them fail from Fly.
A small Cloudflare Worker in `cloudflare/unfurl/` fetches those pages
instead. tumble only calls it after it sees a challenge. Without it,
those links show as plain links without a preview card.

```bash
key="$(openssl rand -hex 32)"
cd cloudflare/unfurl
wrangler deploy # prints the workers.dev URL
echo "$key" | wrangler secret put UNFURL_KEY
fly secrets set TUMBLE_UNFURL_WORKER_URL="https://tumble-unfurl.<subdomain>.workers.dev" \
TUMBLE_UNFURL_WORKER_KEY="$key"
```

**Deploy** (stamps the current git commit into the version banner):

```bash
Expand Down
53 changes: 53 additions & 0 deletions cloudflare/unfurl/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Unfurl relay for tumble's link previews.
//
// Some sites behind Cloudflare serve a challenge page to requests from
// hosting providers, so tumble's server cannot read them. Requests made
// from a Worker usually get through. tumble calls this Worker only after
// it sees a challenge (see scrapeViaWorker in internal/handler/preview.go).
//
// GET /?url=<page> with header X-Unfurl-Key: <UNFURL_KEY>
// Returns the page's status, Content-Type and body. Also cf-mitigated, so
// tumble can tell when the Worker was challenged too.

const USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";

function keyMatches(given, expected) {
const enc = new TextEncoder();
const a = enc.encode(given);
const b = enc.encode(expected);
return a.byteLength === b.byteLength && crypto.subtle.timingSafeEqual(a, b);
}

export default {
async fetch(request, env) {
if (request.method !== "GET") {
return new Response("method not allowed", { status: 405 });
}
if (!env.UNFURL_KEY || !keyMatches(request.headers.get("X-Unfurl-Key") ?? "", env.UNFURL_KEY)) {
return new Response("forbidden", { status: 401 });
}

let target;
try {
target = new URL(new URL(request.url).searchParams.get("url") ?? "");
} catch {
return new Response("url parameter must be an absolute URL", { status: 400 });
}
if (target.protocol !== "http:" && target.protocol !== "https:") {
return new Response("only http(s) URLs are allowed", { status: 400 });
}

const upstream = await fetch(target, {
headers: { "User-Agent": USER_AGENT, Accept: "text/html,*/*;q=0.8" },
redirect: "follow",
});

const headers = new Headers();
for (const name of ["Content-Type", "cf-mitigated"]) {
const value = upstream.headers.get(name);
if (value) headers.set(name, value);
}
return new Response(upstream.body, { status: upstream.status, headers });
},
};
5 changes: 5 additions & 0 deletions cloudflare/unfurl/wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Deploy: wrangler deploy (from this directory, inside the flox env)
# Secret: wrangler secret put UNFURL_KEY
name = "tumble-unfurl"
main = "src/index.js"
compatibility_date = "2026-11-01"
7 changes: 6 additions & 1 deletion internal/assets/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2429,7 +2429,7 @@
"/api/v1/preview": {
"get": {
"summary": "Get OpenGraph Preview",
"description": "Fetches OpenGraph metadata for a URL. Returns cached data if available, otherwise fetches fresh metadata. Supports special handling for YouTube, Reddit, Twitter, Flickr, and OEmbed providers. Pages are tried with several user agents before giving up; 404 and 410 are treated as definitive. Non-HTML resources (PDFs, images) return a basic file card. If the site blocks the server (403, 429, 5xx) but archive.org has a snapshot, the preview is built from the snapshot and includes `archive_url`. Error responses include `error` and, when the site answered, `status`; an error without `status` means the site was unreachable (DNS failure, timeout).",
"description": "Fetches OpenGraph metadata for a URL. Returns cached data if available, otherwise fetches fresh metadata. Supports special handling for YouTube, Reddit, Twitter, Flickr, and OEmbed providers. Pages are tried with several user agents before giving up; 404 and 410 are treated as definitive. Non-HTML resources (PDFs, images) return a basic file card. If the site blocks the server (403, 429, 5xx) but archive.org has a snapshot, the preview is built from the snapshot and includes `archive_url`. If the site serves a Cloudflare challenge and the optional unfurl worker cannot fetch it either, the response is `{\"blocked\": \"true\"}`: the link works in a browser but no preview could be built, and it is not treated as broken. Error responses include `error` and, when the site answered, `status`; an error without `status` means the site was unreachable (DNS failure, timeout).",
"tags": [
"Preview"
],
Expand Down Expand Up @@ -2483,6 +2483,11 @@
"error": {
"type": "string",
"description": "Present when the preview could not be built"
},
"blocked": {
"type": "string",
"enum": ["true"],
"description": "Present when the site blocks the server with a Cloudflare challenge. The link is alive; show it without a card or error badge."
}
}
},
Expand Down
10 changes: 10 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ type Config struct {
WebMaster string `yaml:"webmaster" mapstructure:"webmaster"`
Copyright string `yaml:"copyright" mapstructure:"copyright"`
ActivityPub ActivityPub `yaml:"activitypub" mapstructure:"activitypub"`
UnfurlWorker UnfurlWorker `yaml:"unfurl_worker" mapstructure:"unfurl_worker"`
}

// UnfurlWorker is an optional Cloudflare Worker that fetches pages for the
// preview scraper when a site serves the server a Cloudflare challenge.
// See cloudflare/unfurl/. Both fields must be set to enable it.
type UnfurlWorker struct {
URL string `yaml:"url" mapstructure:"url"`
Key string `yaml:"key" mapstructure:"key"`
}

type ActivityPub struct {
Expand Down Expand Up @@ -86,6 +95,7 @@ func Load(path string) (*Config, error) {
"favicon",
"site_title", "site_description",
"managing_editor", "webmaster", "copyright",
"unfurl_worker.url", "unfurl_worker.key",
} {
_ = v.BindEnv(key)
}
Expand Down
76 changes: 74 additions & 2 deletions internal/handler/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
Expand Down Expand Up @@ -48,6 +50,19 @@ func isDefinitiveStatus(code int) bool {
return code == http.StatusNotFound || code == http.StatusGone
}

// challengeError means the site answered with a Cloudflare challenge page
// (cf-mitigated: challenge). The page is alive; it just will not serve a
// client that cannot run the challenge's JavaScript. Its message matches
// the plain "status %d" errors so existing status parsing keeps working.
type challengeError struct{ status int }

func (e *challengeError) Error() string { return fmt.Sprintf("status %d", e.status) }

func isChallenged(err error) bool {
var c *challengeError
return errors.As(err, &c)
}

// OEmbed Providers Configuration
var oembedProviders = []struct {
Pattern string
Expand Down Expand Up @@ -95,6 +110,10 @@ type OEmbedResponse struct {
// TTL (24h) so errors are retried quickly, while old links get a long TTL (60d).
// A recent link whose error may be transient (403, 429, 5xx) gets 1h.
func isPreviewExpired(cached *data.LinkPreview, linkTimestamp time.Time) bool {
// Blocked links are retried daily in case the block or the worker changes.
if strings.Contains(string(cached.Data), `"blocked":`) {
return time.Since(cached.UpdatedAt) > errorCacheTTLRecent
}
if !strings.Contains(string(cached.Data), `"error":`) {
return time.Since(cached.UpdatedAt) > previewCacheTTL
}
Expand Down Expand Up @@ -442,18 +461,36 @@ func (h *Handler) tryOEmbed(targetURL string) (map[string]string, error) {
func (h *Handler) fetchOGScrape(w http.ResponseWriter, r *http.Request, urlParam string) {
meta, err := h.scrapeWithFallbacks(urlParam)

// A Cloudflare challenge usually means the site blocks our hosting
// provider's IPs. Fetching from inside Cloudflare often gets through.
blocked := isChallenged(err)
if blocked {
if viaWorker, werr := h.scrapeViaWorker(urlParam); werr == nil {
meta, err, blocked = viaWorker, nil, false
} else if h.Config.UnfurlWorker.URL != "" {
log.Printf("preview: unfurl worker failed for %s: %v", urlParam, werr)
}
}

// Bot protection (DataDome, Cloudflare, etc.) blocks servers but not
// browsers, so a 403/429/5xx usually means "alive, but not to us".
// Build the preview from the latest Wayback snapshot instead.
if err != nil {
var status int
if n, _ := fmt.Sscanf(err.Error(), "status %d", &status); n == 1 && !isDefinitiveStatus(status) {
if archived, aerr := h.scrapeArchivedSnapshot(r.Context(), urlParam); aerr == nil {
meta, err = archived, nil
meta, err, blocked = archived, nil, false
}
}
}

// Still challenged: the link works in a browser, so do not report it
// as broken. The frontend shows it as a plain link without a card.
if blocked {
h.cacheAndRespond(w, r, urlParam, map[string]string{"blocked": "true"})
return
}

if err != nil {
w.Header().Set("Content-Type", "application/json")
// If it's a 4xx/5xx error from the helper, we might want to pass that through
Expand Down Expand Up @@ -519,7 +556,33 @@ func (h *Handler) scrapeOpenGraph(targetURL, userAgent string) (map[string]strin
if userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
return h.scrapeRequest(req, targetURL, false)
}

// scrapeViaWorker fetches targetURL through the configured unfurl worker,
// which relays the page's status, Content-Type and body unchanged.
func (h *Handler) scrapeViaWorker(targetURL string) (map[string]string, error) {
cfg := h.Config.UnfurlWorker
if cfg.URL == "" || cfg.Key == "" {
return nil, errors.New("unfurl worker not configured")
}
u, err := url.Parse(cfg.URL)
if err != nil {
return nil, err
}
u.RawQuery = url.Values{"url": {targetURL}}.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-Unfurl-Key", cfg.Key)
return h.scrapeRequest(req, targetURL, true)
}

// scrapeRequest performs req and extracts preview metadata for targetURL.
// viaWorker means req went to the unfurl worker, so the response URL is
// the worker's and not the page's.
func (h *Handler) scrapeRequest(req *http.Request, targetURL string, viaWorker bool) (map[string]string, error) {
client := &http.Client{
Timeout: h.Config.RequestTimeout,
}
Expand All @@ -530,13 +593,22 @@ func (h *Handler) scrapeOpenGraph(targetURL, userAgent string) (map[string]strin
defer resp.Body.Close()

if resp.StatusCode >= 400 {
if resp.Header.Get("Cf-Mitigated") == "challenge" {
return nil, &challengeError{resp.StatusCode}
}
return nil, fmt.Errorf("status %d", resp.StatusCode)
}

// Non-HTML resources (PDFs, images, archives) are alive but have no
// OpenGraph tags. Describe them from the URL instead of parsing bytes.
if ct := resp.Header.Get("Content-Type"); ct != "" && !isHTMLContentType(ct) {
return fileMetadata(resp.Request.URL, ct), nil
fileURL := resp.Request.URL
if viaWorker {
if fileURL, err = url.Parse(targetURL); err != nil {
return nil, err
}
}
return fileMetadata(fileURL, ct), nil
}

// Parse HTML
Expand Down
Loading