mirror of
https://github.com/ajayyy/SponsorBlockServer.git
synced 2025-12-06 11:36:58 +03:00
hook up extra functions to the request validator
This commit is contained in:
@@ -63,13 +63,15 @@ export async function postBranding(req: Request, res: Response) {
|
|||||||
userAgent,
|
userAgent,
|
||||||
userAgentHeader: req.headers["user-agent"],
|
userAgentHeader: req.headers["user-agent"],
|
||||||
videoDuration,
|
videoDuration,
|
||||||
|
videoID,
|
||||||
userID,
|
userID,
|
||||||
service,
|
service,
|
||||||
dearrow: {
|
dearrow: {
|
||||||
title,
|
title,
|
||||||
thumbnail,
|
thumbnail,
|
||||||
downvote,
|
downvote,
|
||||||
}
|
},
|
||||||
|
endpoint: "dearrow-postBranding",
|
||||||
})) {
|
})) {
|
||||||
Logger.warn(`Rejecting submission based on invalid data: ${hashedUserID} ${videoID} ${videoDuration} ${userAgent} ${req.headers["user-agent"]} ${title.title} ${thumbnail.timestamp}`);
|
Logger.warn(`Rejecting submission based on invalid data: ${hashedUserID} ${videoID} ${videoDuration} ${userAgent} ${req.headers["user-agent"]} ${title.title} ${thumbnail.timestamp}`);
|
||||||
res.status(200).send("OK");
|
res.status(200).send("OK");
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import { QueryCacher } from "../utils/queryCacher";
|
|||||||
import { acquireLock } from "../utils/redisLock";
|
import { acquireLock } from "../utils/redisLock";
|
||||||
import { checkBanStatus } from "../utils/checkBan";
|
import { checkBanStatus } from "../utils/checkBan";
|
||||||
import { canSubmitDeArrow } from "../utils/permissions";
|
import { canSubmitDeArrow } from "../utils/permissions";
|
||||||
|
import { isRequestInvalid } from "../utils/requestValidator";
|
||||||
|
import { parseUserAgent } from "../utils/userAgent";
|
||||||
|
|
||||||
interface ExistingVote {
|
interface ExistingVote {
|
||||||
UUID: BrandingUUID;
|
UUID: BrandingUUID;
|
||||||
@@ -22,6 +24,7 @@ interface ExistingVote {
|
|||||||
|
|
||||||
export async function postCasual(req: Request, res: Response) {
|
export async function postCasual(req: Request, res: Response) {
|
||||||
const { videoID, userID, downvote } = req.body as CasualVoteSubmission;
|
const { videoID, userID, downvote } = req.body as CasualVoteSubmission;
|
||||||
|
const userAgent = req.body.userAgent ?? parseUserAgent(req.get("user-agent")) ?? "";
|
||||||
let categories = req.body.categories as CasualCategory[];
|
let categories = req.body.categories as CasualCategory[];
|
||||||
const title = (req.body.title as string)?.toLowerCase();
|
const title = (req.body.title as string)?.toLowerCase();
|
||||||
const service = getService(req.body.service);
|
const service = getService(req.body.service);
|
||||||
@@ -36,6 +39,19 @@ export async function postCasual(req: Request, res: Response) {
|
|||||||
return res.status(400).send("Bad Request");
|
return res.status(400).send("Bad Request");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isRequestInvalid({
|
||||||
|
userID,
|
||||||
|
videoID,
|
||||||
|
userAgent,
|
||||||
|
userAgentHeader: req.headers["user-agent"],
|
||||||
|
casualCategories: categories,
|
||||||
|
service,
|
||||||
|
endpoint: "dearrow-postCasual",
|
||||||
|
})) {
|
||||||
|
Logger.warn(`Casual vote rejected by request validator: ${userAgent} ${req.headers["user-agent"]} ${categories} ${service} ${videoID}`);
|
||||||
|
return res.status(200).send("OK");
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const hashedUserID = await getHashCache(userID);
|
const hashedUserID = await getHashCache(userID);
|
||||||
const hashedVideoID = await getHashCache(videoID, 1);
|
const hashedVideoID = await getHashCache(videoID, 1);
|
||||||
@@ -134,4 +150,4 @@ async function handleExistingVotes(videoID: VideoID, service: Service, titleID:
|
|||||||
[videoID, service, titleID, hashedUserID, hashedIP, category, now]);
|
[videoID, service, titleID, hashedUserID, hashedIP, category, now]);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -514,9 +514,11 @@ export async function postSkipSegments(req: Request, res: Response): Promise<Res
|
|||||||
userAgent,
|
userAgent,
|
||||||
userAgentHeader: req.headers["user-agent"],
|
userAgentHeader: req.headers["user-agent"],
|
||||||
videoDuration,
|
videoDuration,
|
||||||
|
videoID,
|
||||||
userID: paramUserID,
|
userID: paramUserID,
|
||||||
service,
|
service,
|
||||||
segments,
|
segments,
|
||||||
|
endpoint: "sponsorblock-postSkipSegments"
|
||||||
})) {
|
})) {
|
||||||
Logger.warn(`Rejecting submission based on invalid data: ${userID} ${videoID} ${videoDurationParam} ${userAgent} ${req.headers["user-agent"]}`);
|
Logger.warn(`Rejecting submission based on invalid data: ${userID} ${videoID} ${videoDurationParam} ${userAgent} ${req.headers["user-agent"]}`);
|
||||||
return res.status(200).send("OK");
|
return res.status(200).send("OK");
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { getHashCache } from "../utils/getHashCache";
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { isUserBanned } from "../utils/checkBan";
|
import { isUserBanned } from "../utils/checkBan";
|
||||||
import { HashedUserID } from "../types/user.model";
|
import { HashedUserID } from "../types/user.model";
|
||||||
|
import { isRequestInvalid } from "../utils/requestValidator";
|
||||||
|
|
||||||
function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> {
|
function logUserNameChange(userID: string, newUserName: string, oldUserName: string, updatedByAdmin: boolean): Promise<Response> {
|
||||||
return privateDB.prepare("run",
|
return privateDB.prepare("run",
|
||||||
@@ -15,7 +16,7 @@ function logUserNameChange(userID: string, newUserName: string, oldUserName: str
|
|||||||
|
|
||||||
export async function setUsername(req: Request, res: Response): Promise<Response> {
|
export async function setUsername(req: Request, res: Response): Promise<Response> {
|
||||||
const userIDInput = req.query.userID as string;
|
const userIDInput = req.query.userID as string;
|
||||||
const adminUserIDInput = req.query.adminUserID as string;
|
const adminUserIDInput = req.query.adminUserID as string | undefined;
|
||||||
let userName = req.query.username as string;
|
let userName = req.query.username as string;
|
||||||
let hashedUserID: HashedUserID;
|
let hashedUserID: HashedUserID;
|
||||||
|
|
||||||
@@ -29,16 +30,22 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
|||||||
return res.sendStatus(200);
|
return res.sendStatus(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
const timings = [Date.now()];
|
|
||||||
|
|
||||||
// remove unicode control characters from username (example: \n, \r, \t etc.)
|
// remove unicode control characters from username (example: \n, \r, \t etc.)
|
||||||
// source: https://en.wikipedia.org/wiki/Control_character#In_Unicode
|
// source: https://en.wikipedia.org/wiki/Control_character#In_Unicode
|
||||||
// eslint-disable-next-line no-control-regex
|
// eslint-disable-next-line no-control-regex
|
||||||
userName = userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
|
userName = userName.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
|
||||||
|
|
||||||
try {
|
if (isRequestInvalid({
|
||||||
timings.push(Date.now());
|
userAgentHeader: req.headers["user-agent"],
|
||||||
|
userID: adminUserIDInput ?? userIDInput,
|
||||||
|
newUsername: userName,
|
||||||
|
endpoint: "setUsername",
|
||||||
|
})) {
|
||||||
|
Logger.warn(`Username change rejected by request validator: ${userName} ${req.headers["user-agent"]}`);
|
||||||
|
return res.sendStatus(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
if (adminUserIDInput != undefined) {
|
if (adminUserIDInput != undefined) {
|
||||||
//this is the admin controlling the other users account, don't hash the controling account's ID
|
//this is the admin controlling the other users account, don't hash the controling account's ID
|
||||||
hashedUserID = userIDInput as HashedUserID;
|
hashedUserID = userIDInput as HashedUserID;
|
||||||
@@ -55,15 +62,11 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
|||||||
//hash the userID
|
//hash the userID
|
||||||
hashedUserID = await getHashCache(userIDInput) as HashedUserID;
|
hashedUserID = await getHashCache(userIDInput) as HashedUserID;
|
||||||
|
|
||||||
timings.push(Date.now());
|
|
||||||
|
|
||||||
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "userNames" WHERE "userID" = ? AND "locked" = 1`, [hashedUserID]);
|
const row = await db.prepare("get", `SELECT count(*) as "userCount" FROM "userNames" WHERE "userID" = ? AND "locked" = 1`, [hashedUserID]);
|
||||||
if (row.userCount > 0) {
|
if (row.userCount > 0) {
|
||||||
return res.sendStatus(200);
|
return res.sendStatus(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
timings.push(Date.now());
|
|
||||||
|
|
||||||
if (await isUserBanned(hashedUserID)) {
|
if (await isUserBanned(hashedUserID)) {
|
||||||
return res.sendStatus(200);
|
return res.sendStatus(200);
|
||||||
}
|
}
|
||||||
@@ -80,8 +83,6 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
|||||||
const locked = adminUserIDInput === undefined ? 0 : 1;
|
const locked = adminUserIDInput === undefined ? 0 : 1;
|
||||||
let oldUserName = "";
|
let oldUserName = "";
|
||||||
|
|
||||||
timings.push(Date.now());
|
|
||||||
|
|
||||||
if (row?.userName !== undefined) {
|
if (row?.userName !== undefined) {
|
||||||
//already exists, update this row
|
//already exists, update this row
|
||||||
oldUserName = row.userName;
|
oldUserName = row.userName;
|
||||||
@@ -95,14 +96,9 @@ export async function setUsername(req: Request, res: Response): Promise<Response
|
|||||||
await db.prepare("run", `INSERT INTO "userNames"("userID", "userName", "locked") VALUES(?, ?, ?)`, [hashedUserID, userName, locked]);
|
await db.prepare("run", `INSERT INTO "userNames"("userID", "userName", "locked") VALUES(?, ?, ?)`, [hashedUserID, userName, locked]);
|
||||||
}
|
}
|
||||||
|
|
||||||
timings.push(Date.now());
|
|
||||||
|
|
||||||
await logUserNameChange(hashedUserID, userName, oldUserName, adminUserIDInput !== undefined);
|
await logUserNameChange(hashedUserID, userName, oldUserName, adminUserIDInput !== undefined);
|
||||||
|
|
||||||
timings.push(Date.now());
|
return res.sendStatus(200);
|
||||||
|
|
||||||
|
|
||||||
return res.status(200).send(timings.join(", "));
|
|
||||||
} catch (err) /* istanbul ignore next */ {
|
} catch (err) /* istanbul ignore next */ {
|
||||||
Logger.error(err as string);
|
Logger.error(err as string);
|
||||||
return res.sendStatus(500);
|
return res.sendStatus(500);
|
||||||
|
|||||||
@@ -43,24 +43,30 @@ export interface CustomPostgresReadOnlyConfig extends CustomPostgresConfig {
|
|||||||
|
|
||||||
export type ValidatorPattern = string | [string, string];
|
export type ValidatorPattern = string | [string, string];
|
||||||
export interface RequestValidatorRule {
|
export interface RequestValidatorRule {
|
||||||
// universal
|
// mostly universal
|
||||||
userAgent?: ValidatorPattern;
|
userAgent?: ValidatorPattern;
|
||||||
userAgentHeader?: ValidatorPattern;
|
userAgentHeader?: ValidatorPattern;
|
||||||
videoDuration?: ValidatorPattern;
|
videoDuration?: ValidatorPattern;
|
||||||
|
videoID?: ValidatorPattern;
|
||||||
userID?: ValidatorPattern;
|
userID?: ValidatorPattern;
|
||||||
service?: ValidatorPattern;
|
service?: ValidatorPattern;
|
||||||
// sb
|
endpoint?: ValidatorPattern;
|
||||||
|
// sb postSkipSegments
|
||||||
startTime?: ValidatorPattern;
|
startTime?: ValidatorPattern;
|
||||||
endTime?: ValidatorPattern;
|
endTime?: ValidatorPattern;
|
||||||
category?: ValidatorPattern;
|
category?: ValidatorPattern;
|
||||||
actionType?: ValidatorPattern;
|
actionType?: ValidatorPattern;
|
||||||
description?: ValidatorPattern;
|
description?: ValidatorPattern;
|
||||||
// dearrow
|
// dearrow postBranding
|
||||||
title?: ValidatorPattern;
|
title?: ValidatorPattern;
|
||||||
titleOriginal?: boolean;
|
titleOriginal?: boolean;
|
||||||
thumbnailTimestamp?: ValidatorPattern;
|
thumbnailTimestamp?: ValidatorPattern;
|
||||||
thumbnailOriginal?: boolean;
|
thumbnailOriginal?: boolean;
|
||||||
dearrowDownvote?: boolean;
|
dearrowDownvote?: boolean;
|
||||||
|
// postCasual
|
||||||
|
casualCategory?: ValidatorPattern;
|
||||||
|
// setUsername
|
||||||
|
newUsername?: ValidatorPattern;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SBSConfig {
|
export interface SBSConfig {
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { config } from "../config";
|
import { config } from "../config";
|
||||||
import { ThumbnailSubmission, TitleSubmission } from "../types/branding.model";
|
import {
|
||||||
|
CasualCategory,
|
||||||
|
ThumbnailSubmission,
|
||||||
|
TitleSubmission,
|
||||||
|
} from "../types/branding.model";
|
||||||
import { ValidatorPattern, RequestValidatorRule } from "../types/config.model";
|
import { ValidatorPattern, RequestValidatorRule } from "../types/config.model";
|
||||||
import { IncomingSegment } from "../types/segments.model";
|
import { IncomingSegment } from "../types/segments.model";
|
||||||
|
|
||||||
@@ -7,6 +11,7 @@ export interface RequestValidatorInput {
|
|||||||
userAgent?: string;
|
userAgent?: string;
|
||||||
userAgentHeader?: string;
|
userAgentHeader?: string;
|
||||||
videoDuration?: string | number;
|
videoDuration?: string | number;
|
||||||
|
videoID?: string;
|
||||||
userID?: string;
|
userID?: string;
|
||||||
service?: string;
|
service?: string;
|
||||||
segments?: IncomingSegment[];
|
segments?: IncomingSegment[];
|
||||||
@@ -15,10 +20,15 @@ export interface RequestValidatorInput {
|
|||||||
thumbnail?: ThumbnailSubmission;
|
thumbnail?: ThumbnailSubmission;
|
||||||
downvote: boolean;
|
downvote: boolean;
|
||||||
};
|
};
|
||||||
|
casualCategories?: CasualCategory[];
|
||||||
|
newUsername?: string;
|
||||||
|
endpoint?: string;
|
||||||
}
|
}
|
||||||
export type CompiledValidityCheck = (input: RequestValidatorInput) => boolean;
|
export type CompiledValidityCheck = (input: RequestValidatorInput) => boolean;
|
||||||
type CompiledSegmentCheck = (input: IncomingSegment) => boolean;
|
type CompiledSegmentCheck = (input: IncomingSegment) => boolean;
|
||||||
type InputExtractor = (input: RequestValidatorInput) => string | number | undefined | null;
|
type InputExtractor = (
|
||||||
|
input: RequestValidatorInput,
|
||||||
|
) => string | number | undefined | null;
|
||||||
type SegmentExtractor = (input: IncomingSegment) => string | undefined | null;
|
type SegmentExtractor = (input: IncomingSegment) => string | undefined | null;
|
||||||
type BooleanRules = "titleOriginal" | "thumbnailOriginal" | "dearrowDownvote";
|
type BooleanRules = "titleOriginal" | "thumbnailOriginal" | "dearrowDownvote";
|
||||||
type RuleEntry =
|
type RuleEntry =
|
||||||
@@ -27,14 +37,17 @@ type RuleEntry =
|
|||||||
|
|
||||||
let compiledRules: CompiledValidityCheck;
|
let compiledRules: CompiledValidityCheck;
|
||||||
|
|
||||||
|
function patternToRegex(pattern: ValidatorPattern): RegExp {
|
||||||
|
return typeof pattern === "string"
|
||||||
|
? new RegExp(pattern, "i")
|
||||||
|
: new RegExp(...pattern);
|
||||||
|
}
|
||||||
|
|
||||||
function compilePattern(
|
function compilePattern(
|
||||||
pattern: ValidatorPattern,
|
pattern: ValidatorPattern,
|
||||||
extractor: InputExtractor,
|
extractor: InputExtractor,
|
||||||
): CompiledValidityCheck {
|
): CompiledValidityCheck {
|
||||||
const regex =
|
const regex = patternToRegex(pattern);
|
||||||
typeof pattern === "string"
|
|
||||||
? new RegExp(pattern, "i")
|
|
||||||
: new RegExp(...pattern);
|
|
||||||
|
|
||||||
return (input: RequestValidatorInput) => {
|
return (input: RequestValidatorInput) => {
|
||||||
const field = extractor(input);
|
const field = extractor(input);
|
||||||
@@ -47,10 +60,7 @@ function compileSegmentPattern(
|
|||||||
pattern: ValidatorPattern,
|
pattern: ValidatorPattern,
|
||||||
extractor: SegmentExtractor,
|
extractor: SegmentExtractor,
|
||||||
): CompiledSegmentCheck {
|
): CompiledSegmentCheck {
|
||||||
const regex =
|
const regex = patternToRegex(pattern);
|
||||||
typeof pattern === "string"
|
|
||||||
? new RegExp(pattern, "i")
|
|
||||||
: new RegExp(...pattern);
|
|
||||||
|
|
||||||
return (input: IncomingSegment) => {
|
return (input: IncomingSegment) => {
|
||||||
const field = extractor(input);
|
const field = extractor(input);
|
||||||
@@ -93,6 +103,11 @@ export function compileRules(
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
|
case "videoID":
|
||||||
|
ruleComponents.push(
|
||||||
|
compilePattern(rulePattern, (input) => input.videoID),
|
||||||
|
);
|
||||||
|
break;
|
||||||
case "userID":
|
case "userID":
|
||||||
ruleComponents.push(
|
ruleComponents.push(
|
||||||
compilePattern(rulePattern, (input) => input.userID),
|
compilePattern(rulePattern, (input) => input.userID),
|
||||||
@@ -153,7 +168,8 @@ export function compileRules(
|
|||||||
break;
|
break;
|
||||||
case "titleOriginal":
|
case "titleOriginal":
|
||||||
ruleComponents.push(
|
ruleComponents.push(
|
||||||
(input) => input.dearrow?.title?.original === rulePattern,
|
(input) =>
|
||||||
|
input.dearrow?.title?.original === rulePattern,
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
case "thumbnailTimestamp":
|
case "thumbnailTimestamp":
|
||||||
@@ -172,10 +188,39 @@ export function compileRules(
|
|||||||
break;
|
break;
|
||||||
case "dearrowDownvote":
|
case "dearrowDownvote":
|
||||||
ruleComponents.push(
|
ruleComponents.push(
|
||||||
(input) =>
|
(input) => input.dearrow?.downvote === rulePattern,
|
||||||
input.dearrow?.downvote === rulePattern,
|
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
|
case "newUsername":
|
||||||
|
ruleComponents.push(
|
||||||
|
compilePattern(
|
||||||
|
rulePattern,
|
||||||
|
(input) => input.newUsername,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case "endpoint":
|
||||||
|
ruleComponents.push(
|
||||||
|
compilePattern(rulePattern, (input) => input.endpoint),
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case "casualCategory": {
|
||||||
|
const regex = patternToRegex(rulePattern);
|
||||||
|
ruleComponents.push((input) => {
|
||||||
|
if (input.casualCategories === undefined) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const category of input.casualCategories) {
|
||||||
|
if (regex.test(category)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
const _exhaustive: never = ruleKey;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (segmentRuleComponents.length > 0) {
|
if (segmentRuleComponents.length > 0) {
|
||||||
|
|||||||
Reference in New Issue
Block a user