|
| 1 | +/** |
| 2 | + * Publisher RSS/article proxy (Bunny.net Edge Scripting). |
| 3 | + * |
| 4 | + * First-party passthrough for the newsroom pages (see |
| 5 | + * ../../../src/features/newsrooms/). Publisher feeds and article pages send no |
| 6 | + * Access-Control-Allow-Origin header, so a web build cannot fetch them from |
| 7 | + * the browser; this service refetches them server-side and re-serves the body |
| 8 | + * with CORS headers. The app points EXPO_PUBLIC_RSS_PROXY_URL at this host and |
| 9 | + * appends `?url=<target>` itself (see src/features/newsrooms/rss/config.ts). |
| 10 | + * It proxies two kinds of targets: feed XML, and article HTML (for the hero's |
| 11 | + * og:image scrape). |
| 12 | + * |
| 13 | + * Lockdown: only GET, only http(s) targets, and only hosts under the |
| 14 | + * registered publishers' domains - the proxy must not fetch arbitrary URLs on |
| 15 | + * our egress. The allowlist is the build-emitted `newsroom-hosts.json` served |
| 16 | + * next to the web app (scripts/gen-newsroom-hosts.js derives it from the |
| 17 | + * publisher registry), so adding a publisher propagates here on the next web |
| 18 | + * deploy with no proxy change. Redirects are followed manually so a hop |
| 19 | + * cannot escape the allowlist. Responses are cached at the edge so N readers |
| 20 | + * cost roughly one upstream fetch per interval. |
| 21 | + * |
| 22 | + * Config (Bunny dashboard -> script -> Env Configuration), all optional: |
| 23 | + * HOSTS_URL where the emitted allowlist lives |
| 24 | + * (default https://mu.social/newsroom-hosts.json). |
| 25 | + * HOSTS_TTL seconds to cache the fetched allowlist (default 300). |
| 26 | + * ALLOWED_HOSTS comma-separated domain-suffix override; when set, the |
| 27 | + * hosted list is not consulted at all. |
| 28 | + * ALLOWED_ORIGIN Access-Control-Allow-Origin (default *). |
| 29 | + * CACHE_SECONDS edge/browser cache TTL for proxied bodies (default 300). |
| 30 | + */ |
| 31 | +import * as BunnySDK from 'https://esm.sh/@bunny.net/edgescript-sdk@0.11.2' |
| 32 | + |
| 33 | +// Cold-start fallback, used only until the hosted list has been fetched once. |
| 34 | +// Not the source of truth - that is the registry via newsroom-hosts.json. |
| 35 | +const FALLBACK_HOSTS = [ |
| 36 | + 'ft.com', |
| 37 | + 'theverge.com', |
| 38 | + 'wired.com', |
| 39 | + 'nytimes.com', |
| 40 | + 'euractiv.com', |
| 41 | + '404media.co', |
| 42 | + 'cnn.com', |
| 43 | + 'nrc.nl', |
| 44 | + 'propublica.org', |
| 45 | + 'euobserver.com', |
| 46 | + 'theguardian.com', |
| 47 | + 'lemonde.fr', |
| 48 | + 'elpais.com', |
| 49 | + 'next.ink', |
| 50 | +] |
| 51 | + |
| 52 | +const MAX_REDIRECTS = 5 |
| 53 | + |
| 54 | +function env(name: string): string | undefined { |
| 55 | + return Deno.env.get(name) || undefined |
| 56 | +} |
| 57 | + |
| 58 | +function baseHeaders(): Record<string, string> { |
| 59 | + const cacheSeconds = Number(env('CACHE_SECONDS') || '300') |
| 60 | + return { |
| 61 | + 'Access-Control-Allow-Origin': env('ALLOWED_ORIGIN') || '*', |
| 62 | + 'Access-Control-Allow-Methods': 'GET, OPTIONS', |
| 63 | + 'Access-Control-Allow-Headers': 'Accept, Content-Type', |
| 64 | + 'Cache-Control': `public, max-age=60, s-maxage=${cacheSeconds}`, |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +let hostsCache: {hosts: string[]; fetchedAt: number} | null = null |
| 69 | + |
| 70 | +async function allowedHosts(): Promise<string[]> { |
| 71 | + const override = env('ALLOWED_HOSTS') |
| 72 | + if (override) { |
| 73 | + return override |
| 74 | + .split(',') |
| 75 | + .map(s => s.trim().toLowerCase()) |
| 76 | + .filter(Boolean) |
| 77 | + } |
| 78 | + |
| 79 | + const ttlMs = Number(env('HOSTS_TTL') || '300') * 1000 |
| 80 | + if (hostsCache && Date.now() - hostsCache.fetchedAt < ttlMs) { |
| 81 | + return hostsCache.hosts |
| 82 | + } |
| 83 | + try { |
| 84 | + const res = await fetch( |
| 85 | + env('HOSTS_URL') || 'https://mu.social/newsroom-hosts.json', |
| 86 | + {headers: {Accept: 'application/json'}}, |
| 87 | + ) |
| 88 | + if (res.ok) { |
| 89 | + const data = await res.json() |
| 90 | + const hosts = Array.isArray(data?.hosts) |
| 91 | + ? data.hosts |
| 92 | + .map((h: unknown) => String(h).toLowerCase()) |
| 93 | + .filter(Boolean) |
| 94 | + : [] |
| 95 | + if (hosts.length > 0) { |
| 96 | + hostsCache = {hosts, fetchedAt: Date.now()} |
| 97 | + return hosts |
| 98 | + } |
| 99 | + } |
| 100 | + } catch { |
| 101 | + // fall through to stale / fallback below |
| 102 | + } |
| 103 | + // Refresh failed: serve the stale list (and wait a full TTL before retrying, |
| 104 | + // so a broken hosts endpoint does not add a failed fetch to every request). |
| 105 | + if (hostsCache) { |
| 106 | + hostsCache.fetchedAt = Date.now() |
| 107 | + return hostsCache.hosts |
| 108 | + } |
| 109 | + return FALLBACK_HOSTS |
| 110 | +} |
| 111 | + |
| 112 | +function isAllowed(target: URL, hosts: string[]): boolean { |
| 113 | + if (target.protocol !== 'https:' && target.protocol !== 'http:') return false |
| 114 | + const host = target.hostname.toLowerCase() |
| 115 | + return hosts.some(domain => host === domain || host.endsWith('.' + domain)) |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * Fetch with redirects validated hop by hop: a registered feed redirecting to |
| 120 | + * an unregistered host (or a non-http scheme) is refused rather than followed. |
| 121 | + */ |
| 122 | +async function fetchAllowed( |
| 123 | + target: URL, |
| 124 | + hosts: string[], |
| 125 | +): Promise<Response | null> { |
| 126 | + let current = target |
| 127 | + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { |
| 128 | + if (!isAllowed(current, hosts)) return null |
| 129 | + const res = await fetch(current.toString(), { |
| 130 | + redirect: 'manual', |
| 131 | + headers: { |
| 132 | + // Broad Accept: this proxies both feeds (XML) and article pages (HTML). |
| 133 | + Accept: |
| 134 | + 'text/html, application/xhtml+xml, application/rss+xml, application/atom+xml, application/xml, text/xml, */*;q=0.8', |
| 135 | + // Some servers reject requests without a UA. |
| 136 | + 'User-Agent': 'Mozilla/5.0 (compatible; mu-newsrooms-proxy/1.0)', |
| 137 | + }, |
| 138 | + }) |
| 139 | + if (res.status >= 300 && res.status < 400) { |
| 140 | + const location = res.headers.get('location') |
| 141 | + if (!location) return res |
| 142 | + current = new URL(location, current) |
| 143 | + continue |
| 144 | + } |
| 145 | + return res |
| 146 | + } |
| 147 | + return null |
| 148 | +} |
| 149 | + |
| 150 | +BunnySDK.net.http.serve(async (req: Request): Promise<Response> => { |
| 151 | + const headers = baseHeaders() |
| 152 | + |
| 153 | + if (req.method === 'OPTIONS') { |
| 154 | + return new Response(null, {status: 204, headers}) |
| 155 | + } |
| 156 | + if (req.method !== 'GET') { |
| 157 | + return new Response(null, {status: 405, headers}) |
| 158 | + } |
| 159 | + |
| 160 | + let target: URL |
| 161 | + try { |
| 162 | + const raw = new URL(req.url).searchParams.get('url') || '' |
| 163 | + target = new URL(raw) |
| 164 | + } catch { |
| 165 | + return new Response( |
| 166 | + JSON.stringify({error: 'Missing or invalid url param'}), |
| 167 | + {status: 400, headers: {...headers, 'Content-Type': 'application/json'}}, |
| 168 | + ) |
| 169 | + } |
| 170 | + |
| 171 | + const hosts = await allowedHosts() |
| 172 | + if (!isAllowed(target, hosts)) { |
| 173 | + return new Response(JSON.stringify({error: 'Host not allowed'}), { |
| 174 | + status: 403, |
| 175 | + headers: {...headers, 'Content-Type': 'application/json'}, |
| 176 | + }) |
| 177 | + } |
| 178 | + |
| 179 | + try { |
| 180 | + const upstream = await fetchAllowed(target, hosts) |
| 181 | + if (!upstream) { |
| 182 | + return new Response(JSON.stringify({error: 'Host not allowed'}), { |
| 183 | + status: 403, |
| 184 | + headers: {...headers, 'Content-Type': 'application/json'}, |
| 185 | + }) |
| 186 | + } |
| 187 | + const body = await upstream.text() |
| 188 | + return new Response(body, { |
| 189 | + status: upstream.status, |
| 190 | + headers: { |
| 191 | + ...headers, |
| 192 | + 'Content-Type': |
| 193 | + upstream.headers.get('content-type') || |
| 194 | + 'application/xml; charset=utf-8', |
| 195 | + }, |
| 196 | + }) |
| 197 | + } catch (err) { |
| 198 | + return new Response(JSON.stringify({error: String(err)}), { |
| 199 | + status: 502, |
| 200 | + headers: {...headers, 'Content-Type': 'application/json'}, |
| 201 | + }) |
| 202 | + } |
| 203 | +}) |
0 commit comments