api: move accept header check into handler, simplify error handling (#614)

This commit is contained in:
dumbmoron 2024-07-24 17:27:26 +02:00 committed by GitHub
parent b516033f09
commit 85e376bffd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 25 deletions

View file

@ -26,7 +26,7 @@ const corsConfig = env.corsWildcard ? {} : {
export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
const startTime = new Date();
const startTimestamp = startTime.getTime();
const serverInfo = {
version: version,
commit: gitCommit,
@ -81,38 +81,23 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
app.use((req, res, next) => {
try {
decodeURIComponent(req.path)
} catch {
} catch {
return res.redirect('/')
}
next();
})
app.use('/api/json', express.json({
verify: (req, res, buf) => {
if (String(req.header('Accept')) === "application/json") {
if (buf.length > 720) throw new Error();
JSON.parse(buf);
} else {
throw new Error();
}
}
}))
// 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";
const acceptHeader = String(req.header('Accept')) !== "application/json";
if (err || acceptHeader) {
if (acceptHeader) errorText = "invalid accept header";
app.use('/api/json', express.json({ limit: 1024 }));
app.use('/api/json', (err, _, res, next) => {
if (err) {
return res.status(400).json({
status: "error",
text: errorText
text: "invalid json body"
});
} else {
next();
}
})
next();
});
app.post('/api/json', async (req, res) => {
const request = req.body;
@ -123,6 +108,10 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
res.status(status).json(body);
}
if (!acceptRegex.test(req.header('Accept'))) {
return fail('ErrorInvalidAcceptHeader');
}
if (!acceptRegex.test(req.header('Content-Type'))) {
return fail('ErrorInvalidContentType');
}

View file

@ -159,6 +159,7 @@
"UpdateOneMillion": "1 million users and blazing speed",
"ErrorYTAgeRestrict": "this youtube video is age-restricted, so i can't see it. try another one!",
"ErrorYTLogin": "couldn't get this youtube video because it requires an account to view.\n\nthis limitation is done by google to seemingly stop scraping, affecting all 3rd party tools and even their own clients.\n\ntry again, but if issue persists, {ContactLink}.",
"ErrorYTRateLimit": "i got rate limited by youtube. try again in a few seconds, but if issue persists, {ContactLink}."
"ErrorYTRateLimit": "i got rate limited by youtube. try again in a few seconds, but if issue persists, {ContactLink}.",
"ErrorInvalidAcceptHeader": "invalid accept header"
}
}