Proxytest0987 commited on
Commit
38f7420
·
verified ·
1 Parent(s): 141aea0

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +180 -0
server.js ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // server.js — Hugging Face Spaces (Docker) 用 逆プロキシ(軽量 HTML 書換付き)
2
+ // 重要: reCAPTCHA/厳格保護/ログイン必須サイトは動かない場合があります。回避は支援できません。
3
+ const express = require('express');
4
+ const path = require('path');
5
+ const { Readable } = require('stream');
6
+
7
+ const app = express();
8
+ app.disable('x-powered-by');
9
+
10
+ // Top/UI 用の静的配信
11
+ app.use('/public', express.static(path.join(__dirname, 'public'), { maxAge: '1d' }));
12
+
13
+ const SEARCH_ENGINES = {
14
+ ddg: (q) => `https://duckduckgo.com/html/?q=${encodeURIComponent(q)}`,
15
+ brave: (q) => `https://search.brave.com/search?q=${encodeURIComponent(q)}`,
16
+ bing: (q) => `https://www.bing.com/search?q=${encodeURIComponent(q)}`,
17
+ startpg: (q) => `https://www.startpage.com/do/search?q=${encodeURIComponent(q)}`,
18
+ mojeek: (q) => `https://www.mojeek.com/search?q=${encodeURIComponent(q)}`,
19
+ google: (q) => `https://www.google.com/search?q=${encodeURIComponent(q)}` // β: 止まる可能性あり
20
+ };
21
+ const DEFAULT_ENGINE = 'ddg';
22
+
23
+ function isLikelyUrl(v){
24
+ return /^(https?:\/\/)/i.test(v) || (v.includes('.') && !v.includes(' '));
25
+ }
26
+ function proxify(origin, abs, base){
27
+ const u = typeof abs === 'string' ? new URL(abs, origin) : abs;
28
+ const next = new URL('/p', base);
29
+ next.searchParams.set('u', u.href);
30
+ return next.href;
31
+ }
32
+ function removeCookieDomain(v){
33
+ let out = v.replace(/;?\s*Domain=[^;]*/ig, '');
34
+ if (!/;\s*Path=/i.test(out)) out += '; Path=/';
35
+ return out;
36
+ }
37
+ function injectRewriter(body, target, base){
38
+ const abs = (s) => new URL(s, target).href;
39
+ const rewriteAttr = (src, tag, attr) => {
40
+ const rgx = new RegExp(`(<${tag}[^>]*?\\s${attr}=["'])([^"']+)(["'])`, 'ig');
41
+ return src.replace(rgx, (_m, p1, url, p3) => {
42
+ if (!url || url.startsWith('javascript:') || url.startsWith('data:')) return `${p1}${url}${p3}`;
43
+ const to = proxify(target, abs(url), base);
44
+ return `${p1}${to}${p3}`;
45
+ });
46
+ };
47
+ let out = body;
48
+ out = rewriteAttr(out, 'a', 'href');
49
+ out = rewriteAttr(out, 'img', 'src');
50
+ out = rewriteAttr(out, 'script', 'src');
51
+ out = rewriteAttr(out, 'link', 'href');
52
+ out = out.replace(/(<form[^>]*?\saction=["'])([^"']+)(["'])/ig, (_m, p1, url, p3) => {
53
+ const to = proxify(target, abs(url), base);
54
+ return `${p1}${to}${p3}`;
55
+ });
56
+ const headMeta = `<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' data: blob:;"><meta name="referrer" content="no-referrer">`;
57
+ if (out.includes('</head>')) out = out.replace('</head>', `${headMeta}</head>`); else out = headMeta + out;
58
+ return out;
59
+ }
60
+
61
+ // Top ページ
62
+ app.get('/', (_req, res) => {
63
+ res.sendFile(path.join(__dirname, 'public', 'index.html'));
64
+ });
65
+
66
+ // 健康診断
67
+ app.get('/healthz', (_req, res) => res.type('text/plain').send('ok'));
68
+
69
+ // 上流到達診断
70
+ app.get('/diag', async (req, res) => {
71
+ const raw = (req.query.url || '').toString();
72
+ if (!raw) return res.status(400).json({ error: 'missing url' });
73
+ const started = Date.now();
74
+ try {
75
+ const r = await fetch(raw, { method: 'HEAD' });
76
+ res.json({ url: raw, status: r.status, headers: Object.fromEntries(r.headers), time_ms: Date.now()-started });
77
+ } catch (e) {
78
+ res.status(502).json({ url: raw, error: String(e), time_ms: Date.now()-started });
79
+ }
80
+ });
81
+
82
+ // /go はフォームの時だけ body-parser を使う
83
+ app.post('/go', express.urlencoded({ extended: true }), (req, res) => {
84
+ const q = (req.body.q || '').trim();
85
+ const eng = ((req.body.engine || DEFAULT_ENGINE) + '').toLowerCase();
86
+ if (!q) return res.redirect('/');
87
+
88
+ let target = '';
89
+ if (isLikelyUrl(q)) target = /^https?:\/\//i.test(q) ? q : `https://${q}`;
90
+ else target = (SEARCH_ENGINES[eng] || SEARCH_ENGINES[DEFAULT_ENGINE])(q);
91
+
92
+ const p = new URL('/p', `${req.protocol}://${req.get('host')}`);
93
+ p.searchParams.set('u', target);
94
+ res.redirect(p.href);
95
+ });
96
+
97
+ // 生のリクエストボディを読み取る(/p 用)
98
+ async function readRaw(req){
99
+ const chunks = [];
100
+ for await (const c of req) chunks.push(Buffer.from(c));
101
+ return Buffer.concat(chunks);
102
+ }
103
+
104
+ // 逆プロキシ本体
105
+ app.all('/p', async (req, res) => {
106
+ const targetStr = (req.query.u || '').toString();
107
+ if (!targetStr) return res.status(400).send('missing u');
108
+
109
+ let target;
110
+ try { target = new URL(targetStr); }
111
+ catch { return res.status(400).send('bad url'); }
112
+
113
+ // 中継ヘッダ最小化+UA/Lang 整備
114
+ const hop = new Headers();
115
+ for (const [k, v] of Object.entries(req.headers)) {
116
+ const lk = k.toLowerCase();
117
+ if (lk === 'host' || lk === 'connection' || lk.startsWith('cf-') || lk === 'x-forwarded-for' || lk === 'via') continue;
118
+ if (Array.isArray(v)) hop.set(k, v.join(', ')); else if (v) hop.set(k, v);
119
+ }
120
+ if (!hop.get('user-agent')) {
121
+ hop.set('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123 Safari/537.36');
122
+ }
123
+ hop.set('accept-language', 'ja-JP,ja;q=0.9,en-US;q=0.7,en;q=0.6');
124
+ const range = req.headers['range'];
125
+ if (range) hop.set('range', range);
126
+
127
+ const init = {
128
+ method: req.method,
129
+ headers: hop,
130
+ body: (req.method === 'GET' || req.method === 'HEAD') ? undefined : await readRaw(req),
131
+ redirect: 'manual'
132
+ };
133
+
134
+ const up = await fetch(target, init);
135
+
136
+ // リダイレクトの Location を /p?u=... に
137
+ const loc = up.headers.get('location');
138
+ if (up.status >= 300 && up.status < 400 && loc) {
139
+ const abs = new URL(loc, target).href;
140
+ const prox = new URL('/p', `${req.protocol}://${req.get('host')}`); prox.searchParams.set('u', abs);
141
+ for (const [k, v] of up.headers) res.setHeader(k, v);
142
+ res.setHeader('location', prox.href);
143
+ return res.status(up.status).end();
144
+ }
145
+
146
+ // Set-Cookie の Domain を除去
147
+ const rawSet = up.headers.get('set-cookie');
148
+ if (rawSet) {
149
+ res.removeHeader('set-cookie');
150
+ for (const sc of rawSet.split(/,(?=[^ ;]+=)/)) {
151
+ res.append('set-cookie', removeCookieDomain(sc.trim()));
152
+ }
153
+ }
154
+
155
+ // CSP/Frame 制限を弱める(互換性目的)
156
+ res.removeHeader('content-security-policy');
157
+ res.removeHeader('x-frame-options');
158
+
159
+ const ct = up.headers.get('content-type') || '';
160
+ for (const [k, v] of up.headers) {
161
+ const lk = k.toLowerCase();
162
+ if (lk === 'content-security-policy' || lk === 'x-frame-options' || lk === 'set-cookie') continue;
163
+ res.setHeader(k, v);
164
+ }
165
+
166
+ if (ct.includes('text/html')) {
167
+ const text = await up.text();
168
+ const rewritten = injectRewriter(text, target, `${req.protocol}://${req.get('host')}`);
169
+ res.setHeader('content-type', 'text/html; charset=utf-8');
170
+ return res.status(up.status).send(rewritten);
171
+ }
172
+
173
+ if (up.body) return Readable.fromWeb(up.body).pipe(res.status(up.status));
174
+ return res.status(up.status).end();
175
+ });
176
+
177
+ const PORT = process.env.PORT || 7860; // Spaces 既定 7860
178
+ app.listen(PORT, '0.0.0.0', () => {
179
+ console.log('listening on :' + PORT);
180
+ });