Spaces:
Sleeping
Sleeping
Create index.js
Browse files
index.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const fetch = require('node-fetch');
|
| 3 |
+
const cheerio = require('cheerio');
|
| 4 |
+
const { URL } = require('url');
|
| 5 |
+
|
| 6 |
+
const app = express();
|
| 7 |
+
const PORT = 7860;
|
| 8 |
+
|
| 9 |
+
function absolutize(base, relative) {
|
| 10 |
+
try {
|
| 11 |
+
return new URL(relative, base).toString();
|
| 12 |
+
} catch {
|
| 13 |
+
return relative;
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
app.get('/proxy', async (req, res) => {
|
| 18 |
+
const targetUrl = req.query.url;
|
| 19 |
+
if (!targetUrl) {
|
| 20 |
+
return res.status(400).send('Missing ?url= parameter');
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
try {
|
| 24 |
+
const response = await fetch(targetUrl);
|
| 25 |
+
const contentType = response.headers.get('content-type') || '';
|
| 26 |
+
|
| 27 |
+
if (contentType.includes('text/html')) {
|
| 28 |
+
const html = await response.text();
|
| 29 |
+
const $ = cheerio.load(html);
|
| 30 |
+
const base = targetUrl;
|
| 31 |
+
|
| 32 |
+
// 書き換える属性
|
| 33 |
+
const attributes = ['href', 'src', 'action'];
|
| 34 |
+
|
| 35 |
+
$('*').each((i, el) => {
|
| 36 |
+
attributes.forEach(attr => {
|
| 37 |
+
const val = $(el).attr(attr);
|
| 38 |
+
if (val && !val.startsWith('data:') && !val.startsWith('javascript:')) {
|
| 39 |
+
const abs = absolutize(base, val);
|
| 40 |
+
$(el).attr(attr, `/proxy?url=${encodeURIComponent(abs)}`);
|
| 41 |
+
}
|
| 42 |
+
});
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
res.set('Content-Type', 'text/html');
|
| 46 |
+
res.send($.html());
|
| 47 |
+
} else {
|
| 48 |
+
// HTML以外はそのままパイプ
|
| 49 |
+
res.set('Content-Type', contentType);
|
| 50 |
+
response.body.pipe(res);
|
| 51 |
+
}
|
| 52 |
+
} catch (err) {
|
| 53 |
+
console.error(err);
|
| 54 |
+
res.status(500).send('プロキシエラー: ' + err.message);
|
| 55 |
+
}
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
app.listen(PORT, () => {
|
| 59 |
+
console.log(`🌐 Proxy server running at http://localhost:${PORT}`);
|
| 60 |
+
});
|