cobalt/src/core/api.js

195 lines
6.8 KiB
JavaScript
Raw Normal View History

import cors from "cors";
import rateLimit from "express-rate-limit";
import { randomBytes } from "crypto";
const ipSalt = randomBytes(64).toString('hex');
2023-08-04 19:43:12 +01:00
import { version } from "../modules/config.js";
import { getJSON } from "../modules/api.js";
import { apiJSON, checkJSONPost, getIP, languageCode } from "../modules/sub/utils.js";
import { Bright, Cyan } from "../modules/sub/consoleText.js";
import stream from "../modules/stream/stream.js";
import loc from "../localization/manager.js";
import { sha256 } from "../modules/sub/crypto.js";
import { verifyStream } from "../modules/stream/manage.js";
2023-06-05 07:47:03 +01:00
export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
2023-08-04 19:43:12 +01:00
const corsConfig = process.env.cors === '0' ? {
2024-02-16 02:39:31 +00:00
origin: process.env.CORS_URL,
2023-08-04 19:43:12 +01:00
optionsSuccessStatus: 200
} : {};
const apiLimiter = rateLimit({
windowMs: 60000,
max: 20,
2023-08-04 19:43:12 +01:00
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => sha256(getIP(req), ipSalt),
handler: (req, res, next, opt) => {
2023-08-04 19:43:12 +01:00
return res.status(429).json({
2023-08-13 20:51:55 +01:00
"status": "rate-limit",
2023-08-04 19:43:12 +01:00
"text": loc(languageCode(req), 'ErrorRateLimit')
});
}
});
const apiLimiterStream = rateLimit({
windowMs: 60000,
max: 25,
2023-08-04 19:43:12 +01:00
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => sha256(getIP(req), ipSalt),
handler: (req, res, next, opt) => {
2023-08-04 19:43:12 +01:00
return res.status(429).json({
2023-08-13 20:51:55 +01:00
"status": "rate-limit",
2023-08-04 19:43:12 +01:00
"text": loc(languageCode(req), 'ErrorRateLimit')
});
}
});
const startTime = new Date();
const startTimestamp = startTime.getTime();
app.set('trust proxy', ['loopback', 'uniquelocal']);
app.use('/api/:type', cors({
methods: ['GET', 'POST'],
...corsConfig
}));
app.use('/api/json', apiLimiter);
app.use('/api/stream', apiLimiterStream);
app.use('/api/onDemand', apiLimiter);
app.use((req, res, next) => {
try { decodeURIComponent(req.path) } catch (e) { return res.redirect('/') }
next();
});
app.use('/api/json', express.json({
verify: (req, res, buf) => {
2023-08-04 19:43:12 +01:00
let acceptCon = String(req.header('Accept')) === "application/json";
if (acceptCon) {
if (buf.length > 720) throw new Error();
2023-08-04 19:43:12 +01:00
JSON.parse(buf);
} else {
throw new Error();
}
}
}));
2023-08-04 19:43:12 +01:00
// handle express.json errors properly (https://github.com/expressjs/express/issues/4065)
app.use('/api/json', (err, req, res, next) => {
let errorText = "invalid json body";
let acceptCon = String(req.header('Accept')) !== "application/json";
2023-08-04 19:43:12 +01:00
if (err || acceptCon) {
if (acceptCon) errorText = "invalid accept header";
return res.status(400).json({
status: "error",
text: errorText
});
} else {
next();
}
});
app.post('/api/json', async (req, res) => {
try {
let lang = languageCode(req);
2023-08-04 19:43:12 +01:00
let j = apiJSON(0, { t: "bad request" });
try {
2023-08-04 19:43:12 +01:00
let contentCon = String(req.header('Content-Type')) === "application/json";
let request = req.body;
2023-08-04 19:43:12 +01:00
if (contentCon && request.url) {
request.dubLang = request.dubLang ? lang : false;
2023-08-04 19:43:12 +01:00
let chck = checkJSONPost(request);
2023-08-04 19:43:12 +01:00
if (!chck) throw new Error();
j = await getJSON(chck.url, lang, chck);
} else {
2023-08-04 19:43:12 +01:00
j = apiJSON(0, {
t: !contentCon ? "invalid content type header" : loc(lang, 'ErrorNoLink')
});
}
} catch (e) {
j = apiJSON(0, { t: loc(lang, 'ErrorCantProcess') });
}
2023-08-04 19:43:12 +01:00
return res.status(j.status).json(j.body);
} catch (e) {
2023-08-04 19:43:12 +01:00
return res.destroy();
}
});
app.get('/api/:type', (req, res) => {
try {
switch (req.params.type) {
case 'stream':
const q = req.query;
const checkQueries = q.t && q.e && q.h && q.s && q.i;
const checkBaseLength = q.t.length === 21 && q.e.length === 13;
const checkSafeLength = q.h.length === 44 && q.s.length === 344 && q.i.length === 24;
if (checkQueries && checkBaseLength && checkSafeLength) {
let streamInfo = verifyStream(q.t, q.h, q.e, q.s, q.i);
if (streamInfo.error) {
2023-08-04 19:43:12 +01:00
return res.status(streamInfo.status).json(apiJSON(0, { t: streamInfo.error }).body);
}
if (q.p) {
2023-08-04 19:43:12 +01:00
return res.status(200).json({
status: "continue"
});
}
2023-08-04 19:43:12 +01:00
return stream(res, streamInfo);
} else {
2023-08-04 19:43:12 +01:00
let j = apiJSON(0, {
t: "bad request. stream link may be incomplete or corrupted."
2023-08-04 19:43:12 +01:00
})
return res.status(j.status).json(j.body);
}
case 'serverInfo':
2023-08-04 19:43:12 +01:00
return res.status(200).json({
version: version,
commit: gitCommit,
branch: gitBranch,
name: process.env.apiName || "unknown",
url: process.env.apiURL,
cors: process.env?.cors === "0" ? 0 : 1,
startTime: `${startTimestamp}`
});
default:
2023-08-04 19:43:12 +01:00
let j = apiJSON(0, {
t: "unknown response type"
})
return res.status(j.status).json(j.body);
}
} catch (e) {
2023-08-04 19:43:12 +01:00
return res.status(500).json({
status: "error",
text: loc(languageCode(req), 'ErrorCantProcess')
});
}
});
app.get('/api/status', (req, res) => {
res.status(200).end()
});
app.get('/favicon.ico', (req, res) => {
res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
});
app.get('/*', (req, res) => {
res.redirect('/api/json')
});
app.listen(process.env.apiPort || 9000, () => {
2023-08-04 19:43:12 +01:00
console.log(`\n` +
`${Cyan("cobalt")} API ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${process.env.apiURL}`)}\n` +
`Port: ${process.env.apiPort || 9000}\n`
2023-08-04 19:43:12 +01:00
)
});
}