Spaces:
Sleeping
Sleeping
File size: 6,949 Bytes
38f7420 | 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 | // server.js — Hugging Face Spaces (Docker) 用 逆プロキシ(軽量 HTML 書換付き)
// 重要: reCAPTCHA/厳格保護/ログイン必須サイトは動かない場合があります。回避は支援できません。
const express = require('express');
const path = require('path');
const { Readable } = require('stream');
const app = express();
app.disable('x-powered-by');
// Top/UI 用の静的配信
app.use('/public', express.static(path.join(__dirname, 'public'), { maxAge: '1d' }));
const SEARCH_ENGINES = {
ddg: (q) => `https://duckduckgo.com/html/?q=${encodeURIComponent(q)}`,
brave: (q) => `https://search.brave.com/search?q=${encodeURIComponent(q)}`,
bing: (q) => `https://www.bing.com/search?q=${encodeURIComponent(q)}`,
startpg: (q) => `https://www.startpage.com/do/search?q=${encodeURIComponent(q)}`,
mojeek: (q) => `https://www.mojeek.com/search?q=${encodeURIComponent(q)}`,
google: (q) => `https://www.google.com/search?q=${encodeURIComponent(q)}` // β: 止まる可能性あり
};
const DEFAULT_ENGINE = 'ddg';
function isLikelyUrl(v){
return /^(https?:\/\/)/i.test(v) || (v.includes('.') && !v.includes(' '));
}
function proxify(origin, abs, base){
const u = typeof abs === 'string' ? new URL(abs, origin) : abs;
const next = new URL('/p', base);
next.searchParams.set('u', u.href);
return next.href;
}
function removeCookieDomain(v){
let out = v.replace(/;?\s*Domain=[^;]*/ig, '');
if (!/;\s*Path=/i.test(out)) out += '; Path=/';
return out;
}
function injectRewriter(body, target, base){
const abs = (s) => new URL(s, target).href;
const rewriteAttr = (src, tag, attr) => {
const rgx = new RegExp(`(<${tag}[^>]*?\\s${attr}=["'])([^"']+)(["'])`, 'ig');
return src.replace(rgx, (_m, p1, url, p3) => {
if (!url || url.startsWith('javascript:') || url.startsWith('data:')) return `${p1}${url}${p3}`;
const to = proxify(target, abs(url), base);
return `${p1}${to}${p3}`;
});
};
let out = body;
out = rewriteAttr(out, 'a', 'href');
out = rewriteAttr(out, 'img', 'src');
out = rewriteAttr(out, 'script', 'src');
out = rewriteAttr(out, 'link', 'href');
out = out.replace(/(<form[^>]*?\saction=["'])([^"']+)(["'])/ig, (_m, p1, url, p3) => {
const to = proxify(target, abs(url), base);
return `${p1}${to}${p3}`;
});
const headMeta = `<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' data: blob:;"><meta name="referrer" content="no-referrer">`;
if (out.includes('</head>')) out = out.replace('</head>', `${headMeta}</head>`); else out = headMeta + out;
return out;
}
// Top ページ
app.get('/', (_req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// 健康診断
app.get('/healthz', (_req, res) => res.type('text/plain').send('ok'));
// 上流到達診断
app.get('/diag', async (req, res) => {
const raw = (req.query.url || '').toString();
if (!raw) return res.status(400).json({ error: 'missing url' });
const started = Date.now();
try {
const r = await fetch(raw, { method: 'HEAD' });
res.json({ url: raw, status: r.status, headers: Object.fromEntries(r.headers), time_ms: Date.now()-started });
} catch (e) {
res.status(502).json({ url: raw, error: String(e), time_ms: Date.now()-started });
}
});
// /go はフォームの時だけ body-parser を使う
app.post('/go', express.urlencoded({ extended: true }), (req, res) => {
const q = (req.body.q || '').trim();
const eng = ((req.body.engine || DEFAULT_ENGINE) + '').toLowerCase();
if (!q) return res.redirect('/');
let target = '';
if (isLikelyUrl(q)) target = /^https?:\/\//i.test(q) ? q : `https://${q}`;
else target = (SEARCH_ENGINES[eng] || SEARCH_ENGINES[DEFAULT_ENGINE])(q);
const p = new URL('/p', `${req.protocol}://${req.get('host')}`);
p.searchParams.set('u', target);
res.redirect(p.href);
});
// 生のリクエストボディを読み取る(/p 用)
async function readRaw(req){
const chunks = [];
for await (const c of req) chunks.push(Buffer.from(c));
return Buffer.concat(chunks);
}
// 逆プロキシ本体
app.all('/p', async (req, res) => {
const targetStr = (req.query.u || '').toString();
if (!targetStr) return res.status(400).send('missing u');
let target;
try { target = new URL(targetStr); }
catch { return res.status(400).send('bad url'); }
// 中継ヘッダ最小化+UA/Lang 整備
const hop = new Headers();
for (const [k, v] of Object.entries(req.headers)) {
const lk = k.toLowerCase();
if (lk === 'host' || lk === 'connection' || lk.startsWith('cf-') || lk === 'x-forwarded-for' || lk === 'via') continue;
if (Array.isArray(v)) hop.set(k, v.join(', ')); else if (v) hop.set(k, v);
}
if (!hop.get('user-agent')) {
hop.set('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123 Safari/537.36');
}
hop.set('accept-language', 'ja-JP,ja;q=0.9,en-US;q=0.7,en;q=0.6');
const range = req.headers['range'];
if (range) hop.set('range', range);
const init = {
method: req.method,
headers: hop,
body: (req.method === 'GET' || req.method === 'HEAD') ? undefined : await readRaw(req),
redirect: 'manual'
};
const up = await fetch(target, init);
// リダイレクトの Location を /p?u=... に
const loc = up.headers.get('location');
if (up.status >= 300 && up.status < 400 && loc) {
const abs = new URL(loc, target).href;
const prox = new URL('/p', `${req.protocol}://${req.get('host')}`); prox.searchParams.set('u', abs);
for (const [k, v] of up.headers) res.setHeader(k, v);
res.setHeader('location', prox.href);
return res.status(up.status).end();
}
// Set-Cookie の Domain を除去
const rawSet = up.headers.get('set-cookie');
if (rawSet) {
res.removeHeader('set-cookie');
for (const sc of rawSet.split(/,(?=[^ ;]+=)/)) {
res.append('set-cookie', removeCookieDomain(sc.trim()));
}
}
// CSP/Frame 制限を弱める(互換性目的)
res.removeHeader('content-security-policy');
res.removeHeader('x-frame-options');
const ct = up.headers.get('content-type') || '';
for (const [k, v] of up.headers) {
const lk = k.toLowerCase();
if (lk === 'content-security-policy' || lk === 'x-frame-options' || lk === 'set-cookie') continue;
res.setHeader(k, v);
}
if (ct.includes('text/html')) {
const text = await up.text();
const rewritten = injectRewriter(text, target, `${req.protocol}://${req.get('host')}`);
res.setHeader('content-type', 'text/html; charset=utf-8');
return res.status(up.status).send(rewritten);
}
if (up.body) return Readable.fromWeb(up.body).pipe(res.status(up.status));
return res.status(up.status).end();
});
const PORT = process.env.PORT || 7860; // Spaces 既定 7860
app.listen(PORT, '0.0.0.0', () => {
console.log('listening on :' + PORT);
}); |