2023-05-19 12:13:38 +02:00
|
|
|
import cors from "cors";
|
|
|
|
import rateLimit from "express-rate-limit";
|
|
|
|
|
2024-04-29 13:56:05 +02:00
|
|
|
import { env, version } from "../modules/config.js";
|
2024-05-16 10:20:40 +02:00
|
|
|
|
|
|
|
import { generateHmac, generateSalt } from "../modules/sub/crypto.js";
|
2023-05-21 21:13:05 +02:00
|
|
|
import { Bright, Cyan } from "../modules/sub/consoleText.js";
|
2024-05-16 10:20:40 +02:00
|
|
|
import { languageCode } from "../modules/sub/utils.js";
|
2023-05-21 21:13:05 +02:00
|
|
|
import loc from "../localization/manager.js";
|
2024-05-16 10:20:40 +02:00
|
|
|
|
|
|
|
import { createResponse, normalizeRequest, getIP } from "../modules/processing/request.js";
|
2024-04-26 13:53:50 +02:00
|
|
|
import { verifyStream, getInternalStream } from "../modules/stream/manage.js";
|
2024-06-15 18:20:33 +02:00
|
|
|
import { randomizeCiphers } from '../modules/sub/randomize-ciphers.js';
|
2024-05-15 14:45:23 +02:00
|
|
|
import { extract } from "../modules/processing/url.js";
|
2024-05-16 10:20:40 +02:00
|
|
|
import match from "../modules/processing/match.js";
|
|
|
|
import stream from "../modules/stream/stream.js";
|
|
|
|
|
|
|
|
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
|
|
|
|
|
|
|
|
const ipSalt = generateSalt();
|
|
|
|
const corsConfig = env.corsWildcard ? {} : {
|
|
|
|
origin: env.corsURL,
|
|
|
|
optionsSuccessStatus: 200
|
|
|
|
}
|
2023-05-19 12:13:38 +02:00
|
|
|
|
2023-06-05 08:47:03 +02:00
|
|
|
export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
|
2024-05-16 10:20:40 +02:00
|
|
|
const startTime = new Date();
|
|
|
|
const startTimestamp = startTime.getTime();
|
|
|
|
|
|
|
|
const serverInfo = {
|
|
|
|
version: version,
|
|
|
|
commit: gitCommit,
|
|
|
|
branch: gitBranch,
|
|
|
|
name: env.apiName,
|
|
|
|
url: env.apiURL,
|
|
|
|
cors: Number(env.corsWildcard),
|
|
|
|
startTime: `${startTimestamp}`
|
|
|
|
}
|
2023-05-19 12:13:38 +02:00
|
|
|
|
|
|
|
const apiLimiter = rateLimit({
|
2024-05-16 09:54:11 +02:00
|
|
|
windowMs: env.rateLimitWindow * 1000,
|
2024-05-16 09:58:28 +02:00
|
|
|
max: env.rateLimitMax,
|
2023-08-04 20:43:12 +02:00
|
|
|
standardHeaders: true,
|
2023-05-19 12:13:38 +02:00
|
|
|
legacyHeaders: false,
|
2024-03-05 15:55:17 +01:00
|
|
|
keyGenerator: req => generateHmac(getIP(req), ipSalt),
|
2024-05-14 09:08:36 +02:00
|
|
|
handler: (req, res) => {
|
2023-08-04 20:43:12 +02:00
|
|
|
return res.status(429).json({
|
2023-08-13 21:51:55 +02:00
|
|
|
"status": "rate-limit",
|
2024-05-16 17:39:01 +02:00
|
|
|
"text": loc(languageCode(req), 'ErrorRateLimit', env.rateLimitWindow)
|
2023-08-04 20:43:12 +02:00
|
|
|
});
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
|
|
|
|
2023-05-19 12:13:38 +02:00
|
|
|
const apiLimiterStream = rateLimit({
|
2024-05-16 09:54:11 +02:00
|
|
|
windowMs: env.rateLimitWindow * 1000,
|
2024-05-16 09:58:28 +02:00
|
|
|
max: env.rateLimitMax,
|
2023-08-04 20:43:12 +02:00
|
|
|
standardHeaders: true,
|
2023-05-19 12:13:38 +02:00
|
|
|
legacyHeaders: false,
|
2024-03-05 15:55:17 +01:00
|
|
|
keyGenerator: req => generateHmac(getIP(req), ipSalt),
|
2024-05-14 09:08:36 +02:00
|
|
|
handler: (req, res) => {
|
2024-05-15 18:28:09 +02:00
|
|
|
return res.sendStatus(429)
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2023-05-19 12:13:38 +02:00
|
|
|
|
2023-07-25 21:46:25 +02:00
|
|
|
app.set('trust proxy', ['loopback', 'uniquelocal']);
|
|
|
|
|
2024-05-16 09:54:11 +02:00
|
|
|
app.use('/api', cors({
|
2024-03-05 13:14:26 +01:00
|
|
|
methods: ['GET', 'POST'],
|
2024-05-16 09:59:53 +02:00
|
|
|
exposedHeaders: [
|
|
|
|
'Ratelimit-Limit',
|
|
|
|
'Ratelimit-Policy',
|
|
|
|
'Ratelimit-Remaining',
|
|
|
|
'Ratelimit-Reset'
|
|
|
|
],
|
|
|
|
...corsConfig,
|
2024-05-15 18:28:09 +02:00
|
|
|
}))
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-05-19 12:13:38 +02:00
|
|
|
app.use('/api/json', apiLimiter);
|
|
|
|
app.use('/api/stream', apiLimiterStream);
|
|
|
|
|
|
|
|
app.use((req, res, next) => {
|
2024-05-16 06:19:07 +02:00
|
|
|
try {
|
|
|
|
decodeURIComponent(req.path)
|
|
|
|
} catch {
|
|
|
|
return res.redirect('/')
|
|
|
|
}
|
2023-05-19 12:13:38 +02:00
|
|
|
next();
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-05-19 12:13:38 +02:00
|
|
|
app.use('/api/json', express.json({
|
|
|
|
verify: (req, res, buf) => {
|
2024-05-16 06:19:07 +02:00
|
|
|
if (String(req.header('Accept')) === "application/json") {
|
2023-05-19 12:13:38 +02:00
|
|
|
if (buf.length > 720) throw new Error();
|
2023-08-04 20:43:12 +02:00
|
|
|
JSON.parse(buf);
|
|
|
|
} else {
|
|
|
|
throw new Error();
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|
|
|
|
}
|
2024-05-15 18:28:09 +02:00
|
|
|
}))
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-08-04 20:43:12 +02:00
|
|
|
// handle express.json errors properly (https://github.com/expressjs/express/issues/4065)
|
|
|
|
app.use('/api/json', (err, req, res, next) => {
|
2024-05-15 18:51:26 +02:00
|
|
|
let errorText = "invalid json body";
|
2024-05-15 18:28:09 +02:00
|
|
|
const acceptHeader = String(req.header('Accept')) !== "application/json";
|
2023-05-19 12:13:38 +02:00
|
|
|
|
2024-05-15 18:28:09 +02:00
|
|
|
if (err || acceptHeader) {
|
|
|
|
if (acceptHeader) errorText = "invalid accept header";
|
2023-08-04 20:43:12 +02:00
|
|
|
return res.status(400).json({
|
|
|
|
status: "error",
|
|
|
|
text: errorText
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-05-19 12:13:38 +02:00
|
|
|
app.post('/api/json', async (req, res) => {
|
2024-05-15 15:29:18 +02:00
|
|
|
const request = req.body;
|
|
|
|
const lang = languageCode(req);
|
2024-05-15 18:28:09 +02:00
|
|
|
|
2024-05-15 15:29:18 +02:00
|
|
|
const fail = (t) => {
|
2024-05-15 17:39:44 +02:00
|
|
|
const { status, body } = createResponse("error", { t: loc(lang, t) });
|
2024-05-15 15:29:18 +02:00
|
|
|
res.status(status).json(body);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!acceptRegex.test(req.header('Content-Type'))) {
|
|
|
|
return fail('ErrorInvalidContentType');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!request.url) {
|
|
|
|
return fail('ErrorNoLink');
|
|
|
|
}
|
|
|
|
|
|
|
|
request.dubLang = request.dubLang ? lang : false;
|
2024-05-15 19:03:33 +02:00
|
|
|
const normalizedRequest = normalizeRequest(request);
|
2024-05-15 15:29:18 +02:00
|
|
|
if (!normalizedRequest) {
|
|
|
|
return fail('ErrorCantProcess');
|
|
|
|
}
|
|
|
|
|
|
|
|
const parsed = extract(normalizedRequest.url);
|
|
|
|
if (parsed === null) {
|
|
|
|
return fail('ErrorUnsupported');
|
|
|
|
}
|
|
|
|
|
2023-05-19 12:13:38 +02:00
|
|
|
try {
|
2024-05-15 15:29:18 +02:00
|
|
|
const result = await match(
|
|
|
|
parsed.host, parsed.patternMatch, lang, normalizedRequest
|
|
|
|
);
|
2024-05-15 14:45:23 +02:00
|
|
|
|
2024-05-15 15:29:18 +02:00
|
|
|
res.status(result.status).json(result.body);
|
|
|
|
} catch {
|
|
|
|
fail('ErrorSomethingWentWrong');
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
app.get('/api/stream', (req, res) => {
|
|
|
|
const id = String(req.query.id);
|
|
|
|
const exp = String(req.query.exp);
|
|
|
|
const sig = String(req.query.sig);
|
|
|
|
const sec = String(req.query.sec);
|
|
|
|
const iv = String(req.query.iv);
|
|
|
|
|
|
|
|
const checkQueries = id && exp && sig && sec && iv;
|
|
|
|
const checkBaseLength = id.length === 21 && exp.length === 13;
|
|
|
|
const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
|
|
|
|
|
2024-05-22 18:45:32 +02:00
|
|
|
if (!checkQueries || !checkBaseLength || !checkSafeLength) {
|
|
|
|
return res.sendStatus(400);
|
2024-05-15 18:28:09 +02:00
|
|
|
}
|
2024-05-22 18:45:32 +02:00
|
|
|
|
|
|
|
// rate limit probe, will not return json after 8.0
|
|
|
|
if (req.query.p) {
|
|
|
|
return res.status(200).json({
|
|
|
|
status: "continue"
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const streamInfo = verifyStream(id, sig, exp, sec, iv);
|
|
|
|
if (!streamInfo?.service) {
|
|
|
|
return res.sendStatus(streamInfo.status);
|
|
|
|
}
|
|
|
|
return stream(res, streamInfo);
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2023-05-19 12:13:38 +02:00
|
|
|
|
2024-05-15 18:28:09 +02:00
|
|
|
app.get('/api/istream', (req, res) => {
|
2024-05-22 18:45:32 +02:00
|
|
|
if (!req.ip.endsWith('127.0.0.1')) {
|
|
|
|
return res.sendStatus(403);
|
2024-05-15 18:28:09 +02:00
|
|
|
}
|
|
|
|
|
2024-05-22 18:45:32 +02:00
|
|
|
if (String(req.query.id).length !== 21) {
|
|
|
|
return res.sendStatus(400);
|
|
|
|
}
|
|
|
|
|
|
|
|
const streamInfo = getInternalStream(req.query.id);
|
|
|
|
if (!streamInfo) {
|
|
|
|
return res.sendStatus(404);
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|
2024-05-22 18:45:32 +02:00
|
|
|
|
2024-07-06 13:36:25 +02:00
|
|
|
streamInfo.headers = new Map([
|
|
|
|
streamInfo.headers || {},
|
|
|
|
req.headers
|
|
|
|
]);
|
2024-05-22 18:45:32 +02:00
|
|
|
|
|
|
|
return stream(res, { type: 'internal', ...streamInfo });
|
|
|
|
})
|
|
|
|
|
|
|
|
app.get('/api/serverInfo', (_, res) => {
|
|
|
|
return res.status(200).json(serverInfo);
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-05-21 21:13:05 +02:00
|
|
|
app.get('/favicon.ico', (req, res) => {
|
|
|
|
res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2024-03-05 13:14:26 +01:00
|
|
|
|
2023-05-21 21:13:05 +02:00
|
|
|
app.get('/*', (req, res) => {
|
2024-05-15 18:28:09 +02:00
|
|
|
res.redirect('/api/serverInfo')
|
|
|
|
})
|
2023-05-19 12:13:38 +02:00
|
|
|
|
2024-06-15 18:20:33 +02:00
|
|
|
randomizeCiphers();
|
|
|
|
setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
|
|
|
|
|
2024-05-13 20:20:10 +02:00
|
|
|
app.listen(env.apiPort, env.listenAddress, () => {
|
2023-08-04 20:43:12 +02:00
|
|
|
console.log(`\n` +
|
|
|
|
`${Cyan("cobalt")} API ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
|
|
|
|
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
|
2024-04-29 13:56:05 +02:00
|
|
|
`URL: ${Cyan(`${env.apiURL}`)}\n` +
|
|
|
|
`Port: ${env.apiPort}\n`
|
2023-08-04 20:43:12 +02:00
|
|
|
)
|
2024-05-15 18:28:09 +02:00
|
|
|
})
|
2023-05-19 12:13:38 +02:00
|
|
|
}
|