1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
|
const CONSTANTS = { ALLOWED_ORIGINS: [ "https://yourdomain.com", "https://www.yourdomain.com", "http://localhost:4000", "http://localhost:3000", "http://127.0.0.1:4000", "http://127.0.0.1:3000" ], ALLOWED_DOMAIN: 'douban.com', REQUEST_TIMEOUT: 10000, CACHE_TTL: 1800, CDN_CACHE_TTL: 3600, USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" };
function hashCode(str) { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return Math.abs(hash).toString(36); }
function createCorsHeaders(origin) { return { "Access-Control-Allow-Origin": origin, "Access-Control-Allow-Methods": "GET, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }; }
function isValidOrigin(origin) { return origin && ( CONSTANTS.ALLOWED_ORIGINS.includes(origin) || /^https?:\/\/localhost:\d+$/.test(origin) || /^https?:\/\/127\.0\.0\.1:\d+$/.test(origin) ); }
function isValidReferer(referer) { return !referer || referer.includes("yourdomain.com") || referer.includes("localhost") || referer.includes("127.0.0.1"); }
function logRequest(request, origin, status, message = '') { const shouldLog = status >= 400 || message.includes('denied') || message.includes('error'); if (shouldLog) { const log = { timestamp: new Date().toISOString(), method: request.method, origin: origin || 'unknown', status: status, message: message }; console.log(`[Worker] ${JSON.stringify(log)}`); } }
export default { async fetch(request) { const origin = request.headers.get("Origin"); const referer = request.headers.get("Referer"); if (!isValidOrigin(origin) || !isValidReferer(referer)) { logRequest(request, origin, 403, 'Access denied - invalid origin or referer'); return new Response("Access denied", { status: 403, headers: { "Content-Type": "text/plain", "X-Debug-Info": `Origin: ${origin || 'null'}, Referer: ${referer || 'null'}`, }, }); }
if (request.method === "OPTIONS") { return new Response(null, { status: 204, headers: createCorsHeaders(origin), }); }
const url = new URL(request.url); const feedUrl = url.searchParams.get("feed"); if (!feedUrl) { return new Response("Missing ?feed parameter", { status: 400, headers: { "Access-Control-Allow-Origin": origin }, }); }
try { const parsedFeedUrl = new URL(feedUrl); if (!parsedFeedUrl.hostname.endsWith(CONSTANTS.ALLOWED_DOMAIN)) { return new Response(`Invalid feed URL: only ${CONSTANTS.ALLOWED_DOMAIN} domains are allowed`, { status: 400, headers: { "Access-Control-Allow-Origin": origin }, }); } } catch (error) { return new Response("Invalid feed URL format", { status: 400, headers: { "Access-Control-Allow-Origin": origin }, }); }
const cache = caches.default; const cacheKey = new Request(request.url, request); let cached = await cache.match(cacheKey); if (cached) { const newHeaders = new Headers(cached.headers); newHeaders.set("Access-Control-Allow-Origin", origin); newHeaders.set("X-Cache-Status", "HIT"); newHeaders.set("X-Cache-Date", cached.headers.get("Last-Modified") || "unknown"); return new Response(cached.body, { status: cached.status, statusText: cached.statusText, headers: newHeaders, }); }
const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), CONSTANTS.REQUEST_TIMEOUT);
let resp; try { resp = await fetch(feedUrl, { signal: controller.signal, headers: { "User-Agent": CONSTANTS.USER_AGENT, Referer: "https://www.douban.com/", "Accept": "application/rss+xml, application/xml, text/xml", "Accept-Encoding": "gzip, deflate", }, }); clearTimeout(timeoutId);
if (!resp.ok) { return new Response(`Failed to fetch feed: ${resp.status}`, { status: resp.status, headers: { "Access-Control-Allow-Origin": origin }, }); } } catch (error) { clearTimeout(timeoutId); if (error.name === 'AbortError') { return new Response("Request timeout", { status: 408, headers: { "Access-Control-Allow-Origin": origin }, }); } return new Response(`Network error: ${error.message}`, { status: 500, headers: { "Access-Control-Allow-Origin": origin }, }); }
const xml = await resp.text();
const items = []; const itemRegex = /<item>([\s\S]*?)<\/item>/g; let match; while ((match = itemRegex.exec(xml)) !== null) { const itemXml = match[1];
const getTag = (tag) => { const re = new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`); const m = itemXml.match(re); return m ? m[1].trim() : ""; };
const description = getTag("description");
const linkMatch = description.match(/<a href="([^"]+)"/); const posterMatch = description.match(/<img src="([^"]+)"/);
const pTags = description.match(/<p>([\s\S]*?)<\/p>/g) || []; let recommend = ''; let tags = []; let remark = '';
pTags.forEach(p => { const content = p.replace(/<\/?p>/g, '').trim(); if (content.startsWith('推荐:')) { recommend = content.substring('推荐:'.length).trim(); } else if (content.startsWith('标签:')) { tags = content.substring('标签:'.length).trim().split(/\s+/).filter(t => t); } else if (content.startsWith('备注:')) { remark = content.substring('备注:'.length).trim(); } });
items.push({ title: getTag("title"), link: getTag("link"), pubDate: getTag("pubDate"), guid: getTag("guid"), description, movieLink: linkMatch ? linkMatch[1] : "", poster: posterMatch ? posterMatch[1] : "", recommend: recommend, tags: tags, remark: remark, }); }
const jsonResp = new Response(JSON.stringify(items, null, 2), { headers: { "Content-Type": "application/json; charset=utf-8", "Access-Control-Allow-Origin": origin, "Cache-Control": `public, max-age=${CONSTANTS.CACHE_TTL}, s-maxage=${CONSTANTS.CDN_CACHE_TTL}`, "ETag": `"${hashCode(JSON.stringify(items))}"`, "Last-Modified": new Date().toUTCString(), "X-Cache-Status": "MISS", "X-Data-Source": "douban-fresh", }, });
cache.put(cacheKey, jsonResp.clone()).catch(err => console.error('Cache error:', err));
return jsonResp; }, };
|