Skip to content

Commit

Permalink
refactor: fix eslint violations
Browse files Browse the repository at this point in the history
  • Loading branch information
pmstss committed Aug 26, 2024
1 parent c9ab5ca commit d3f37d0
Show file tree
Hide file tree
Showing 17 changed files with 49 additions and 69 deletions.
2 changes: 0 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ module.exports = {
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
Expand Down
7 changes: 3 additions & 4 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ concurrency:
cancel-in-progress: true

jobs:
test:
check:
runs-on: ubuntu-latest
strategy:
matrix:
Expand All @@ -39,9 +39,8 @@ jobs:
- name: Check format
run: npm run format

# commented till fixing lint errors
# - name: Lint
# run: npm run lint
- name: Lint
run: npm run lint

- name: Build
run: npm run build
6 changes: 3 additions & 3 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export class AppController {
type: Object,
status: 200,
})
getSecrets(): Object {
getSecrets(): Record<string, string> {
const secrets = {
codeclimate:
'CODECLIMATE_REPO_TOKEN=62864c476ade6ab9d10d0ce0901ae2c211924852a28c5f960ae5165c1fdfec73',
Expand Down Expand Up @@ -290,8 +290,8 @@ export class AppController {

this.logger.debug(`Creating a JSON with a nesting depth of ${depth}`);

var tmpObj: object = {};
var jsonObj: object = { '0': 'Leaf' };
let tmpObj = {};
let jsonObj: Record<string, string> = { '0': 'Leaf' };
for (let i = 1; i < depth; i++) {
tmpObj = {};
tmpObj[i.toString()] = Object.assign({}, jsonObj);
Expand Down
6 changes: 0 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,6 @@ export class AuthService {
),
'utf8',
);
const jwkPublicKey = fs.readFileSync(
this.configService.get<string>(
AuthModuleConfigProperties.ENV_JWK_PUBLIC_KEY_LOCATION,
),
'utf8',
);
const jwkPublicJson = JSON.parse(
fs.readFileSync(
this.configService.get<string>(
Expand Down
2 changes: 1 addition & 1 deletion src/auth/jwt/jwt.token.with.sql.kid.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class JwtTokenWithSqlKIDProcessor extends JwtTokenProcessor {
async validateToken(token: string): Promise<any> {
this.log.debug('Call validateToken');

const [header, payload] = this.parse(token);
const [header] = this.parse(token);

const query = JwtTokenWithSqlKIDProcessor.KID_FETCH_QUERY(
this.key,
Expand Down
2 changes: 1 addition & 1 deletion src/auth/jwt/jwt.token.with.x5c.key.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class JwtTokenWithX5CKeyProcessor extends JwtTokenProcessor {

async validateToken(token: string): Promise<any> {
this.log.debug('Call validateToken');
const [header, payload] = this.parse(token);
const [header] = this.parse(token);

const keys = header.x5c;
const keyLike = await jose.importPKCS8(keys[0], 'RS256');
Expand Down
2 changes: 1 addition & 1 deletion src/auth/jwt/jwt.token.with.x5u.key.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class JwtTokenWithX5UKeyProcessor extends JwtTokenProcessor {

async validateToken(token: string): Promise<any> {
this.log.debug('Call validateToken');
const [header, payload] = this.parse(token);
const [header] = this.parse(token);

const url = header.x5u;
this.log.debug(`Loading key from url ${url}`);
Expand Down
1 change: 0 additions & 1 deletion src/components/headers.configurator.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {
CallHandler,
ExecutionContext,
Injectable,
InternalServerErrorException,
Logger,
NestInterceptor,
} from '@nestjs/common';
Expand Down
7 changes: 3 additions & 4 deletions src/email/email.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
SWAGGER_DESC_SEND_EMAIL,
} from './email.controller.swagger.desc';
import splitUriIntoParamsPPVulnerable from '../utils/url';
import { boolean } from 'webidl-conversions';

@Controller('/api/email')
@ApiTags('Emails controller')
Expand Down Expand Up @@ -64,7 +63,7 @@ export class EmailController {
this.logger.log('Sending a support Email');

// This is defined here intentionally so we don't override responseJson.status after the prototype pollution has occurred
let responseJson = {
const responseJson = {
message: {},
status: HttpStatus.OK,
};
Expand All @@ -85,14 +84,14 @@ export class EmailController {
this.logger.debug(`Raw query ${rawQuery}`);

// "Use" the status code
let uriParams: any = splitUriIntoParamsPPVulnerable(rawQuery);
const uriParams: any = splitUriIntoParamsPPVulnerable(rawQuery);
if (uriParams?.status) {
responseJson.status = uriParams.status;
}

const mailSubject = `Support email regarding "${subject}"`;
const mailBody = `Hi ${name},\nWe recieved your email and just wanted to let you know we're on it!\n\nYour original inquiry was:\n**********************\n${content}\n**********************`;
let didSucceed = await this.emailService.sendRawEmail(
const didSucceed = await this.emailService.sendRawEmail(
this.BC_EMAIL_ADDRESS,
to,
mailSubject,
Expand Down
22 changes: 9 additions & 13 deletions src/email/email.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const axios = require('axios');

import axios from 'axios';
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import { forEach } from 'lodash';
import { json } from 'sequelize';
const nodemailer = require('nodemailer');
import { createTransport } from 'nodemailer';

@Injectable()
export class EmailService {
Expand All @@ -19,9 +17,7 @@ export class EmailService {
},
};

private readonly transporter = nodemailer.createTransport(
this.smtpServerDetails,
);
private readonly transporter = createTransport(this.smtpServerDetails);

private readonly MAIL_CATCHER_MESSAGES_URL =
'http://mailcatcher:1080/messages';
Expand All @@ -45,7 +41,7 @@ export class EmailService {
body,
);

let response = await this.transporter.sendMail(mailOptions);
const response = await this.transporter.sendMail(mailOptions);

if (response.err) {
this.logger.debug(`Failed sending email. Error: ${response.err}`);
Expand Down Expand Up @@ -116,7 +112,7 @@ export class EmailService {

rawContent += `\n${body}\n`;

let mailOptions = {
const mailOptions = {
envelope: {
from: parsedFrom,
to: parsedTo,
Expand All @@ -132,7 +128,7 @@ export class EmailService {
async getEmails(withSource): Promise<json> {
this.logger.debug(`Fetching all emails from MailCatcher`);

let emails = await axios
const emails = await axios
.get(this.MAIL_CATCHER_MESSAGES_URL)
.then((res) =>
res.status == HttpStatus.OK
Expand All @@ -142,7 +138,7 @@ export class EmailService {

if (withSource) {
this.logger.debug(`Fetching sources of Emails`);
for (let email of emails) {
for (const email of emails) {
email['source'] = await this.getEmailSource(email['id']);
}
}
Expand All @@ -151,7 +147,7 @@ export class EmailService {
}

private async getEmailSource(emailId): Promise<string> {
let sourceUrl = `${this.MAIL_CATCHER_MESSAGES_URL}/${emailId}.source`;
const sourceUrl = `${this.MAIL_CATCHER_MESSAGES_URL}/${emailId}.source`;

return await axios
.get(sourceUrl)
Expand All @@ -167,7 +163,7 @@ export class EmailService {
);
}

async deleteEmails(): Promise<Boolean> {
async deleteEmails(): Promise<boolean> {
this.logger.debug(`Deleting all emails from MailCatcher`);

return await axios
Expand Down
1 change: 0 additions & 1 deletion src/file/file.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Controller,
Delete,
Get,
Headers,
HttpStatus,
Logger,
Put,
Expand Down
16 changes: 8 additions & 8 deletions src/partners/partners.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class PartnersController {
@ApiOkResponse({
type: String,
})
async queryPartnersRaw(@Query('xpath') xpath: string): Promise<String> {
async queryPartnersRaw(@Query('xpath') xpath: string): Promise<string> {
this.logger.debug(`Getting partners with xpath expression "${xpath}"`);

try {
Expand Down Expand Up @@ -79,14 +79,14 @@ export class PartnersController {
async partnerLogin(
@Query('username') username: string,
@Query('password') password: string,
): Promise<String> {
): Promise<string> {
this.logger.debug(
`Trying to login partner with username ${username} using password ${password}`,
);

try {
let xpath = `//partners/partner[username/text()='${username}' and password/text()='${password}']/*`;
let xmlStr = this.partnersService.getPartnersProperties(xpath);
const xpath = `//partners/partner[username/text()='${username}' and password/text()='${password}']/*`;
const xmlStr = this.partnersService.getPartnersProperties(xpath);

// Check if account's data contains any information - If not, the login failed!
if (
Expand All @@ -97,7 +97,7 @@ export class PartnersController {

return xmlStr;
} catch (err) {
let strErr = err.toString();
const strErr = err.toString();
if (strErr.includes('Unterminated string literal')) {
err = 'Error in XPath expression';
}
Expand All @@ -123,14 +123,14 @@ export class PartnersController {
@ApiOkResponse({
type: String,
})
async searchPartners(@Query('keyword') keyword: string): Promise<String> {
async searchPartners(@Query('keyword') keyword: string): Promise<string> {
this.logger.debug(`Searching partner names by the keyword "${keyword}"`);

try {
let xpath = `//partners/partner/name[contains(., '${keyword}')]`;
const xpath = `//partners/partner/name[contains(., '${keyword}')]`;
return this.partnersService.getPartnersProperties(xpath);
} catch (err) {
let strErr = err.toString();
const strErr = err.toString();
if (
strErr.includes('XPath parse error') ||
strErr.includes('Unterminated string literal')
Expand Down
15 changes: 7 additions & 8 deletions src/partners/partners.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';

const xpath = require('xpath');
const dom = require('xmldom').DOMParser;
import { DOMParser } from 'xmldom';
import xpath, { SelectReturnType } from 'xpath';

@Injectable()
export class PartnersService {
Expand Down Expand Up @@ -53,8 +52,8 @@ export class PartnersService {
</partners>
`;

private getPartnersXMLObj(): object {
let partnersXMLObj = new dom().parseFromString(
private getPartnersXMLObj(): Node {
const partnersXMLObj = new DOMParser().parseFromString(
this.XML_AUTHORS_STR,
'text/xml',
);
Expand All @@ -63,8 +62,8 @@ export class PartnersService {

private selectPartnerPropertiesByXPATH(
xpathExpression: string,
): Array<string> {
let partnersXMLObj = this.getPartnersXMLObj();
): SelectReturnType {
const partnersXMLObj = this.getPartnersXMLObj();
return xpath.select(xpathExpression, partnersXMLObj);
}

Expand All @@ -79,7 +78,7 @@ export class PartnersService {
this.logger.debug(
`xmlNodes's type wasn't 'Array', and it's value was: ${xmlNodes}`,
);
xmlNodes = Array();
xmlNodes = [];
} else {
this.logger.debug(`Raw xpath xmlNodes value is: ${xmlNodes}`);
}
Expand Down
1 change: 0 additions & 1 deletion src/products/products.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
Controller,
Get,
Header,
Logger,
UseGuards,
Headers,
Expand Down
1 change: 0 additions & 1 deletion src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ export class UsersController {
async deleteUserPhotoById(
@Param('id') id: number,
@Query('isAdmin') isAdminParam: string,
@Res({ passthrough: true }) res: FastifyReply,
) {
isAdminParam = isAdminParam.toLowerCase();
const isAdmin =
Expand Down
2 changes: 1 addition & 1 deletion src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class UsersService {
private readonly usersRepository: EntityRepository<User>,
) {}

async createUser(user: UserDto, isBasicUser: boolean = true): Promise<User> {
async createUser(user: UserDto, isBasicUser = true): Promise<User> {
this.log.debug(`Called createUser`);

const u = new User();
Expand Down
25 changes: 12 additions & 13 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Taken from PortSwigger's prototype pollution labs
// VULNERABLE TO PROTOTYPE POLLUTION!
var splitUriIntoParamsPPVulnerable = (params, coerce = undefined) => {
const splitUriIntoParamsPPVulnerable = (params, coerce = undefined) => {
if (params.charAt(0) === '?') {
params = params.substring(1);
}

var obj = {},
coerce_types = { true: !0, false: !1, null: null };
const obj = {};
const coerce_types = { true: !0, false: !1, null: null };

if (!params) {
return obj;
Expand All @@ -16,13 +16,13 @@ var splitUriIntoParamsPPVulnerable = (params, coerce = undefined) => {
.replace(/\+/g, ' ')
.split('&')
.forEach(function (v) {
var param = v.split('='),
key = decodeURIComponent(param[0]),
val,
cur = obj,
i = 0,
keys = key.split(']['),
keys_last = keys.length - 1;
const param = v.split('=');
let key = decodeURIComponent(param[0]);
let keys = key.split('][');
let keys_last = keys.length - 1;
let val;
let cur: any = obj;
let i = 0;

if (/\[/.test(keys[0]) && /\]$/.test(keys[keys_last])) {
keys[keys_last] = keys[keys_last].replace(/\]$/, '');
Expand All @@ -48,12 +48,11 @@ var splitUriIntoParamsPPVulnerable = (params, coerce = undefined) => {

if (keys_last) {
for (; i <= keys_last; i++) {
//@ts-ignore
key = keys[i] === '' ? cur.length : keys[i];
cur = cur[key] =
i < keys_last
? //@ts-ignore
cur[key] || (keys[i + 1] && isNaN(keys[i + 1]) ? {} : [])
? cur[key] ||
(keys[i + 1] && isNaN(keys[i + 1] as any) ? {} : [])
: val;
}
} else {
Expand Down

0 comments on commit d3f37d0

Please sign in to comment.