Last active
May 10, 2024 09:00
-
-
Save thanksshu/1ffcff844453321d0e94b5ae463c05b2 to your computer and use it in GitHub Desktop.
BiliRoaming Alibaba Cloud FC Node.js script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file BiliRoaming Alibaba Cloud FC Node.js script, need a layer with "axios" | |
* @author thanksshu | |
* @license MIT | |
*/ | |
'use strict'; | |
const axios = require('axios').default; | |
const TARGET_URL = 'https://api.bilibili.com'; | |
const TIMEOUT = 5000; // ms | |
exports.handler = (req, resp, _) => { | |
// log inbound request | |
console.log({ | |
// 'headers': req.headers, | |
'path': req.path, | |
'queries': req.queries, | |
'method': req.method, | |
'referer': req.headers['referer'], | |
'biliroaming': req.headers['x-from-biliroaming'], | |
'ip': req.clientIP, | |
}); | |
/* check request url */ | |
// web? y-> pass | |
// n-> app? y-> header? y-> pass | |
// n-> 404 n-> 403 | |
if (req.path !== '/pgc/player/web/playurl') { | |
if (req.path !== '/pgc/player/api/playurl') { | |
console.log('Not found'); | |
resp.setStatusCode(404); | |
resp.send('Not found'); | |
return; | |
} else if (req.headers['x-from-biliroaming'] === undefined) { | |
console.log('Forbidden'); | |
resp.setStatusCode(403); | |
resp.send('Forbidden'); | |
return; | |
} | |
} | |
/* send proxy request */ | |
// remove some headers | |
const { 'host': _host, 'referer': _referer, 'user-agent': _userAgent, ...headers } = req.headers; | |
axios.request({ | |
method: req.method, | |
url: TARGET_URL + req.path, | |
headers: headers, | |
params: req.queries, | |
data: req.body, | |
timeout: TIMEOUT, | |
}).then((response) => { | |
// log proxy response | |
console.log({ | |
// 'headers': response.headers, | |
'status': response.status, | |
'data': response.data, | |
}); | |
resp.setStatusCode(response.status); | |
// remove access-control-allow-credentials header which causes strange problems | |
const { 'access-control-allow-credentials': _aCAC, ...respHeaders } = response.headers | |
for (const key in respHeaders) { | |
resp.setHeader(key, respHeaders[key]); | |
} | |
resp.send(JSON.stringify(response.data)); | |
}).catch((error) => { | |
console.log(error); | |
resp.setStatusCode(502); | |
resp.send("Upstream error"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment