diff --git a/src/ts/server/requestUtils.ts b/src/ts/server/requestUtils.ts index 59148e3..0a13c1d 100644 --- a/src/ts/server/requestUtils.ts +++ b/src/ts/server/requestUtils.ts @@ -1,6 +1,7 @@ import { Request, Response, RequestHandler } from 'express'; import * as fs from 'fs'; import * as path from 'path'; +import { timingSafeEqual } from 'crypto'; import { formatDistanceToNow } from 'date-fns'; import rateLimit from 'express-rate-limit'; import { noop } from 'lodash'; @@ -68,8 +69,18 @@ export const offline = (settings: Settings): RequestHandler => (_req, res, next) } }; +function isValidApiToken(token: string | undefined, expected: string | undefined) { + if (!token || !expected) { + return false; + } + + const a = Buffer.from(token); + const b = Buffer.from(expected); + return a.length === b.length && timingSafeEqual(a, b); +} + export const internal = (config: AppConfig, server: ServerConfig): RequestHandler => (req, res, next) => { - if (req.get('api-token') === config.token) { + if (isValidApiToken(req.get('api-token'), config.token)) { next(null); } else { @@ -160,7 +171,10 @@ export function wrap(server: ServerConfig, handle: (req: Request) => any): Reque export function wrapApi(server: ServerConfig, api: any) { return wrap(server, ({ body: { method, args = [] } }) => { - if (api[method]) { + if ( + typeof method === 'string' && !(method in Object.prototype) && typeof api[method] === 'function' && + Array.isArray(args) + ) { return api[method](...args); } else {