cobalt-7/src/cobalt.js

184 lines
7.6 KiB
JavaScript
Raw Normal View History

import "dotenv/config";
2022-07-08 18:17:56 +00:00
import express from "express";
import cors from "cors";
2022-07-08 18:17:56 +00:00
import * as fs from "fs";
import rateLimit from "express-rate-limit";
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4); // go up another level (get rid of src/)
import { getCurrentBranch, shortCommit } from "./modules/sub/currentCommit.js";
import { appName, genericUserAgent, version } from "./modules/config.js";
2022-07-08 18:17:56 +00:00
import { getJSON } from "./modules/api.js";
import { apiJSON, checkJSONPost, languageCode } from "./modules/sub/utils.js";
import { Bright, Cyan, Green, Red } from "./modules/sub/consoleText.js";
2022-07-08 18:17:56 +00:00
import stream from "./modules/stream/stream.js";
import loc from "./localization/manager.js";
import { buildFront } from "./modules/build.js";
2022-09-11 15:04:06 +00:00
import { changelogHistory } from "./modules/pageRender/onDemand.js";
import { sha256 } from "./modules/sub/crypto.js";
import findRendered from "./modules/pageRender/findRendered.js";
2022-07-08 18:17:56 +00:00
const commitHash = shortCommit();
const branch = getCurrentBranch();
2022-07-08 18:17:56 +00:00
const app = express();
app.disable('x-powered-by');
app.use('/api/:type', cors())
if (fs.existsSync('./.env') && process.env.selfURL && process.env.streamSalt && process.env.port) {
2022-07-08 18:17:56 +00:00
const apiLimiter = rateLimit({
windowMs: 60000,
2023-03-24 18:14:44 +00:00
max: 25,
standardHeaders: false,
2022-07-08 18:17:56 +00:00
legacyHeaders: false,
keyGenerator: (req, res) => sha256(req.ip.replace('::ffff:', ''), process.env.streamSalt),
2022-07-08 18:17:56 +00:00
handler: (req, res, next, opt) => {
res.status(429).json({ "status": "error", "text": loc(languageCode(req), 'ErrorRateLimit') });
return;
2022-07-08 18:17:56 +00:00
}
2022-12-06 19:21:07 +00:00
});
2022-07-08 18:17:56 +00:00
const apiLimiterStream = rateLimit({
windowMs: 60000,
2023-03-24 18:14:44 +00:00
max: 28,
standardHeaders: false,
2022-07-08 18:17:56 +00:00
legacyHeaders: false,
keyGenerator: (req, res) => sha256(req.ip.replace('::ffff:', ''), process.env.streamSalt),
2022-07-08 18:17:56 +00:00
handler: (req, res, next, opt) => {
res.status(429).json({ "status": "error", "text": loc(languageCode(req), 'ErrorRateLimit') });
return;
2022-07-08 18:17:56 +00:00
}
2022-12-06 19:21:07 +00:00
});
2022-07-08 18:17:56 +00:00
await buildFront(commitHash, branch);
2023-03-24 18:14:44 +00:00
app.use('/api/json', apiLimiter);
2022-07-08 18:17:56 +00:00
app.use('/api/stream', apiLimiterStream);
2023-03-24 18:14:44 +00:00
app.use('/api/onDemand', apiLimiter);
app.use('/', express.static('./min'));
app.use('/', express.static('./src/front'));
2022-07-08 18:17:56 +00:00
app.use((req, res, next) => {
try { decodeURIComponent(req.path) } catch (e) { return res.redirect(process.env.selfURL) }
2022-07-08 18:17:56 +00:00
next();
});
app.use((req, res, next) => {
if (req.header("user-agent") && req.header("user-agent").includes("Trident")) res.destroy();
next();
});
app.use('/api/json', express.json({
verify: (req, res, buf) => {
try {
JSON.parse(buf);
if (buf.length > 720) throw new Error();
if (String(req.header('Content-Type')) !== "application/json") {
res.status(400).json({ 'status': 'error', 'text': 'invalid content type header' });
return;
}
if (String(req.header('Accept')) !== "application/json") {
res.status(400).json({ 'status': 'error', 'text': 'invalid accept header' });
return;
}
} catch(e) {
res.status(400).json({ 'status': 'error', 'text': 'invalid json body.' });
return;
}
}
}));
app.post('/api/json', async (req, res) => {
try {
let ip = sha256(req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip.replace('::ffff:', ''), process.env.streamSalt);
2023-02-26 16:49:25 +00:00
let lang = languageCode(req);
let j = apiJSON(0, { t: "Bad request" });
try {
let request = req.body;
if (request.url) {
request.dubLang = request.dubLang ? lang : false;
let chck = checkJSONPost(request);
if (chck) chck["ip"] = ip;
j = chck ? await getJSON(chck["url"], lang, chck) : apiJSON(0, { t: loc(lang, 'ErrorCouldntFetch') });
} else {
j = apiJSON(0, { t: loc(lang, 'ErrorNoLink') });
}
} catch (e) {
j = apiJSON(0, { t: loc(lang, 'ErrorCantProcess') });
}
res.status(j.status).json(j.body);
return;
} catch (e) {
res.status(500).json({ 'status': 'error', 'text': loc(languageCode(req), 'ErrorCantProcess') });
return;
}
});
app.get('/api/:type', (req, res) => {
2022-07-08 18:17:56 +00:00
try {
let ip = sha256(req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip.replace('::ffff:', ''), process.env.streamSalt);
2022-07-08 18:17:56 +00:00
switch (req.params.type) {
case 'stream':
if (req.query.p) {
res.status(200).json({ "status": "continue" });
return;
} else if (req.query.t && req.query.h && req.query.e) {
stream(res, ip, req.query.t, req.query.h, req.query.e);
2022-07-08 18:17:56 +00:00
} else {
2022-09-03 15:32:39 +00:00
let j = apiJSON(0, { t: "no stream id" })
2022-07-08 18:17:56 +00:00
res.status(j.status).json(j.body);
return;
2022-07-08 18:17:56 +00:00
}
break;
2022-09-11 15:04:06 +00:00
case 'onDemand':
if (req.query.blockId) {
let blockId = req.query.blockId.slice(0, 3)
let r, j;
switch(blockId) {
case "0":
r = changelogHistory();
j = r ? apiJSON(3, { t: r }) : apiJSON(0, { t: "couldn't render this block" })
break;
default:
j = apiJSON(0, { t: "couldn't find a block with this id" })
break;
}
res.status(j.status).json(j.body);
} else {
let j = apiJSON(0, { t: "no block id" })
res.status(j.status).json(j.body);
}
break;
2022-07-08 18:17:56 +00:00
default:
2022-09-11 15:04:06 +00:00
let j = apiJSON(0, { t: "unknown response type" })
2022-07-08 18:17:56 +00:00
res.status(j.status).json(j.body);
break;
}
} catch (e) {
res.status(500).json({ 'status': 'error', 'text': loc(languageCode(req), 'ErrorCantProcess') });
return;
2022-07-08 18:17:56 +00:00
}
});
2022-09-01 13:51:18 +00:00
app.get("/api", (req, res) => {
2022-07-08 18:17:56 +00:00
res.redirect('/api/json')
});
2022-09-01 13:51:18 +00:00
app.get("/", (req, res) => {
res.sendFile(`${__dirname}/${findRendered(languageCode(req), req.header('user-agent') ? req.header('user-agent') : genericUserAgent)}`);
2022-07-08 18:17:56 +00:00
});
2022-09-01 13:51:18 +00:00
app.get("/favicon.ico", (req, res) => {
2022-07-08 18:17:56 +00:00
res.redirect('/icons/favicon.ico');
});
2022-09-01 13:51:18 +00:00
app.get("/*", (req, res) => {
2022-07-08 18:17:56 +00:00
res.redirect('/')
});
2022-07-08 18:17:56 +00:00
app.listen(process.env.port, () => {
let startTime = new Date();
console.log(`\n${Cyan(appName)} ${Bright(`v.${version}-${commitHash} (${branch})`)}\nStart time: ${Bright(`${startTime.toUTCString()} (${Math.floor(new Date().getTime())})`)}\n\nURL: ${Cyan(`${process.env.selfURL}`)}\nPort: ${process.env.port}\n`)
2022-07-08 18:17:56 +00:00
});
} else {
console.log(Red(`cobalt hasn't been configured yet or configuration is invalid.\n`) + Bright(`please run the setup script to fix this: `) + Green(`npm run setup`))
}