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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
| /** * Cloudflare Worker: Google Calendar 全域通配反代 * - 默认路径:代理 https://calendar.google.com 的 HTML * - /proxy/{scheme}/{host}/{path}?{query}:通配代理任意目标(scheme: http|https) * - HTMLRewriter:改写 HTML 中所有 *.google*.com 等静态资源地址为 /proxy 路径 * - 动态拦截:注入脚本,统一把运行时的 fetch / XHR / WebSocket / EventSource 指向 /proxy */
const PROXY_PREFIX = "/proxy/"; const HTML_TYPES = ["text/html", "application/xhtml+xml"];
// 需要代理的域名后缀白名单(尽量覆盖 Google 生态) const HOST_WHITELIST_SUFFIX = [ ".google.com", ".googleapis.com", ".gstatic.com", ".googleusercontent.com", ".ggpht.com", ".gvt1.com", ".gvt2.com", ];
export default { async fetch(request, env, ctx) { const reqUrl = new URL(request.url);
// 1) 处理通配代理入口 /proxy/{scheme}/{host}/... if (reqUrl.pathname.startsWith(PROXY_PREFIX)) { return handleProxy(request, reqUrl); }
// 2) 默认:把非 /proxy 的请求转到 calendar.google.com(嵌入页) // 然后用 HTMLRewriter 改写里面的资源链接 const upstreamUrl = new URL(request.url); upstreamUrl.hostname = "calendar.google.com";
// 保持同样的 path/query const upstreamResp = await fetch(upstreamUrl.toString(), { method: request.method, headers: stripHopByHop(request.headers), body: request.body, redirect: "follow", });
const ct = upstreamResp.headers.get("content-type") || ""; // 非 HTML:去掉限制性头,原样透传 if (!HTML_TYPES.some(t => ct.includes(t))) { return passthroughResponse(upstreamResp); }
// HTML:改写静态链接 + 注入动态拦截脚本 const rewriter = new HTMLRewriter() // 统一改写常见链接属性 .on("a[href]", new AttrRewriter("href")) .on("link[href]", new AttrRewriter("href")) .on("script[src]", new AttrRewriter("src", { removeIntegrity: true })) .on("img[src]", new AttrRewriter("src")) .on("source[srcset]", new SrcSetRewriter("srcset")) .on("img[srcset]", new SrcSetRewriter("srcset")) .on("iframe[src]", new AttrRewriter("src")) .on("form[action]", new AttrRewriter("action")) // style 属性里的 url(...) .on("*[style]", new StyleAttrRewriter("style")) // <style> 标签内的 url(...) .on("style", new StyleTagRewriter()) // 移除可能阻止内嵌的 CSP/XFO meta .on('meta[http-equiv="Content-Security-Policy"]', { element: el => el.remove() }) .on("head", new HeadInjector()) .on("body", new BodyInjector());
const rewritten = rewriter.transform(upstreamResp); return addFriendlyHeaders(rewritten); }, };
/* ---------------- Utils ---------------- */
function isWhitelistedHost(hostname) { const host = hostname.toLowerCase(); return HOST_WHITELIST_SUFFIX.some(sfx => host.endsWith(sfx)); }
// 统一把绝对 URL 改写为 /proxy/{scheme}/{host}/{path}?{query} function toProxyUrl(absUrl, origin) { try { // 处理协议相对 // 开头 if (absUrl.startsWith("//")) { absUrl = "https:" + absUrl; } const u = new URL(absUrl); if (!isWhitelistedHost(u.hostname)) return absUrl; // 非白名单,不动 const scheme = u.protocol.replace(":", ""); return `${origin}${PROXY_PREFIX}${scheme}/${u.hostname}${u.pathname}${u.search}`; } catch { // 非法/相对地址,不改写 return absUrl; } }
// 去除 hop-by-hop 头 function stripHopByHop(headers) { const h = new Headers(headers); [ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", // 有些站点会对 accept-encoding 进行压缩协商,HTMLRewriter 可处理解压,这里保留即可 ].forEach(k => h.delete(k)); return h; }
// 透传并放宽安全头 async function passthroughResponse(resp) { const buf = await resp.arrayBuffer(); const h = new Headers(resp.headers); // 允许 iframe 嵌入 h.delete("x-frame-options"); h.delete("content-security-policy"); h.delete("content-security-policy-report-only"); // 放宽跨域(其实 iframe 同源下并不需要,但留着更稳) h.set("access-control-allow-origin", "*"); h.set("access-control-allow-credentials", "true"); h.set("access-control-allow-headers", "*"); h.set("access-control-allow-methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS"); return new Response(buf, { status: resp.status, statusText: resp.statusText, headers: h }); }
// 在 HTML 响应上附加友好头(同上) function addFriendlyHeaders(resp) { const h = new Headers(resp.headers); h.delete("x-frame-options"); h.delete("content-security-policy"); h.delete("content-security-policy-report-only"); h.set("access-control-allow-origin", "*"); h.set("access-control-allow-credentials", "true"); h.set("access-control-allow-headers", "*"); h.set("access-control-allow-methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS"); return new Response(resp.body, { status: resp.status, statusText: resp.statusText, headers: h }); }
// /proxy/{scheme}/{host}/... 入口 async function handleProxy(request, reqUrl) { const seg = reqUrl.pathname.slice(PROXY_PREFIX.length).split("/"); if (seg.length < 2) { return new Response("Invalid proxy path", { status: 400 }); } const scheme = seg[0]; // http | https const host = seg[1]; const pathRest = "/" + seg.slice(2).join("/"); const target = `${scheme}://${host}${pathRest}${reqUrl.search || ""}`;
// 非白名单域名直接拒绝,避免被滥用成开放代理 if (!isWhitelistedHost(host)) { return new Response("Host not allowed", { status: 403 }); }
// 预检请求快速放行 if (request.method === "OPTIONS") { return new Response(null, { status: 204, headers: { "access-control-allow-origin": "*", "access-control-allow-headers": "*", "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS", }, }); }
const upstreamResp = await fetch(target, { method: request.method, headers: stripHopByHop(request.headers), body: request.body, redirect: "follow", });
const ct = upstreamResp.headers.get("content-type") || ""; if (!HTML_TYPES.some(t => ct.includes(t))) { return passthroughResponse(upstreamResp); }
// 即使是通过 /proxy 拿到的 HTML,也执行改写(以防页面里继续生成绝对链接) const rewriter = new HTMLRewriter() .on("a[href]", new AttrRewriter("href")) .on("link[href]", new AttrRewriter("href")) .on("script[src]", new AttrRewriter("src", { removeIntegrity: true })) .on("img[src]", new AttrRewriter("src")) .on("source[srcset]", new SrcSetRewriter("srcset")) .on("img[srcset]", new SrcSetRewriter("srcset")) .on("iframe[src]", new AttrRewriter("src")) .on("form[action]", new AttrRewriter("action")) .on("*[style]", new StyleAttrRewriter("style")) .on("style", new StyleTagRewriter()) .on('meta[http-equiv="Content-Security-Policy"]', { element: el => el.remove() }) .on("head", new HeadInjector()) .on("body", new BodyInjector());
const rewritten = rewriter.transform(upstreamResp); return addFriendlyHeaders(rewritten); }
/* --------------- HTMLRewriter Handlers --------------- */
// 改写单个属性(href/src/action/...) class AttrRewriter { constructor(attr, opts = {}) { this.attr = attr; this.opts = opts; } element(el) { const val = el.getAttribute(this.attr); if (!val) return; const origin = getOrigin(el); const newVal = toProxyUrl(val, origin); if (newVal !== val) { el.setAttribute(this.attr, newVal); // SRI 会因改写 URL 失效,干脆去掉 if (this.opts.removeIntegrity) { el.removeAttribute("integrity"); el.removeAttribute("crossorigin"); } } } }
// 改写 srcset(多 URL) class SrcSetRewriter { constructor(attr) { this.attr = attr; } element(el) { const val = el.getAttribute(this.attr); if (!val) return; const origin = getOrigin(el); const parts = val.split(",").map(s => s.trim()).map(entry => { const [u, rest] = entry.split(/\s+/, 2); const prox = toProxyUrl(u, origin); return rest ? `${prox} ${rest}` : prox; }); el.setAttribute(this.attr, parts.join(", ")); } }
// 改写 style="background-image:url(...)" 等 class StyleAttrRewriter { constructor(attr) { this.attr = attr; } element(el) { const val = el.getAttribute(this.attr); if (!val) return; const origin = getOrigin(el); const replaced = replaceCssUrls(val, origin); if (replaced !== val) el.setAttribute(this.attr, replaced); } }
// 改写 <style> 内的 url(...) class StyleTagRewriter { element(el) { el.onEndTag(t => { /* no-op, need text stage */ }); } text(t) { const origin = getOriginFromTextTransformer(this); const old = t.text; const rep = replaceCssUrls(old, origin); if (rep !== old) t.replace(rep); } }
// 往 <head> 注入一些 meta/脚本(如需) class HeadInjector { element(el) { // 可按需注入 <meta>,例如 viewport 或去除 nosniff } }
// 在 </body> 之前注入“动态拦截脚本” class BodyInjector { element(el) { el.append(DYNAMIC_SHIM, { html: true }); } }
// 获取当前文档 origin(用于生成 /proxy 绝对 URL) function getOrigin(el) { // HTMLRewriter 没有直接给 origin,只能用一个安全兜底: // 由浏览器加载时,location.origin 就是当前 Worker 绑定域名 return ""; } // StyleTagRewriter 文本阶段拿不到 window,这里同样返回空,toProxyUrl 会拼接 origin="" => 从浏览器解析成相对地址 function getOriginFromTextTransformer(_) { return ""; }
// 把 CSS 文本里的 url("https://...") 改写为 /proxy function replaceCssUrls(cssText, origin) { // 捕获 url(...) 中的引号或无引号 URL return cssText.replace(/url\(\s*(['"]?)(https?:\/\/[^'")\s]+)\1\s*\)/g, (m, q, u) => { const prox = toProxyUrl(u, origin); return `url(${q}${prox}${q})`; }); }
/* --------------- 动态请求“猴补丁” --------------- */
const DYNAMIC_SHIM = ` <script> (function(){ const HOST_WHITELIST_SUFFIX = ${JSON.stringify(HOST_WHITELIST_SUFFIX)}; const PROXY_PREFIX = ${JSON.stringify(PROXY_PREFIX)}; function isWhitelisted(h){ h = (h||"").toLowerCase(); return HOST_WHITELIST_SUFFIX.some(s=>h.endsWith(s)); } function toProxy(u){ try{ if (typeof u !== 'string') return u; if (u.startsWith('/')) return u; // 相对路径不动 if (u.startsWith('//')) u = 'https:' + u; const url = new URL(u, location.href); if (!isWhitelisted(url.hostname)) return u; const scheme = url.protocol.replace(':',''); return PROXY_PREFIX + scheme + '/' + url.hostname + url.pathname + url.search; }catch(e){return u;} }
// fetch 拦截 const _fetch = window.fetch; window.fetch = function(input, init){ if (typeof input === 'string') { input = toProxy(input); } else if (input && input.url) { input = new Request(toProxy(input.url), input); } return _fetch(input, init); };
// XHR 拦截 const _open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url){ try { url = toProxy(url); } catch(e){} return _open.apply(this, [method, url, ...Array.prototype.slice.call(arguments,2)]); };
// EventSource 拦截 const _ES = window.EventSource; if (_ES) { window.EventSource = function(url, cfg){ return new _ES(toProxy(url), cfg); } window.EventSource.prototype = _ES.prototype; }
// WebSocket 拦截(如有) const _WS = window.WebSocket; if (_WS) { window.WebSocket = function(url, proto){ // WS/ WSS 不在此代理范围,如有需要,可在 Worker 添加 ws 反代 // 这里仅避免 google ws 直连(Calendar 通常不用 ws) try{ if (typeof url === 'string'){ const u = new URL(url, location.href); if (isWhitelisted(u.hostname)) { // 阻止直连(可直接抛错/改为长轮询) throw new Error('Blocked direct WebSocket to ' + u.hostname); } } }catch(e){} return new _WS(url, proto); } window.WebSocket.prototype = _WS.prototype; }
// 替换 Document 中现存的绝对链接(极端兜底) function rewriteDom(){ const sel = ['a[href]','link[href]','script[src]','img[src]','source[srcset]','img[srcset]','iframe[src]','form[action]']; sel.forEach(s=>{ document.querySelectorAll(s).forEach(el=>{ ['href','src','action','srcset'].forEach(attr=>{ if (!el.hasAttribute(attr)) return; const v = el.getAttribute(attr); const nv = toProxy(v); if (v !== nv) { el.setAttribute(attr, nv); el.removeAttribute('integrity'); el.removeAttribute('crossorigin'); } }); }); }); } document.addEventListener('DOMContentLoaded', rewriteDom); window.addEventListener('load', rewriteDom); })(); </script> `;
|