feat: fixed eslint and resolved all eslint issues

This commit is contained in:
Akhil Mohan
2024-01-30 22:30:42 +05:30
parent 7c4dd5000f
commit 5855cc660a
147 changed files with 1165 additions and 938 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ import { getConfig } from "@app/lib/config/env";
export const globalRateLimiterCfg = (): RateLimitPluginOptions => {
const appCfg = getConfig();
const redis = appCfg.isRedisConfigured
? new Redis(appCfg.REDIS_URL as string, { connectTimeout: 500, maxRetriesPerRequest: 1 })
? new Redis(appCfg.REDIS_URL, { connectTimeout: 500, maxRetriesPerRequest: 1 })
: null;
return {
@@ -106,9 +106,7 @@ export const injectIdentity = fp(async (server: FastifyZodProvider) => {
break;
}
case AuthMode.SERVICE_TOKEN: {
const serviceToken = await server.services.serviceToken.fnValidateServiceToken(
token as string
);
const serviceToken = await server.services.serviceToken.fnValidateServiceToken(token);
req.auth = {
authMode: AuthMode.SERVICE_TOKEN as const,
serviceToken,
@@ -1,12 +1,17 @@
import { FastifyRequest } from "fastify";
import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { UnauthorizedError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
export const verifySuperAdmin = async <T extends FastifyRequest>(req: T) => {
export const verifySuperAdmin = <T extends FastifyRequest>(
req: T,
_res: FastifyReply,
done: HookHandlerDoneFunction
) => {
if (req.auth.actor !== ActorType.USER || !req.auth.user.superAdmin)
throw new UnauthorizedError({
name: "Unauthorized access",
message: "Requires superadmin access"
});
done();
};
@@ -1,11 +1,11 @@
import { FastifyRequest } from "fastify";
import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { UnauthorizedError } from "@app/lib/errors";
import { AuthMode } from "@app/services/auth/auth-type";
export const verifyAuth =
<T extends FastifyRequest>(authStrats: AuthMode[]) =>
async (req: T) => {
(req: T, _res: FastifyReply, done: HookHandlerDoneFunction) => {
if (!Array.isArray(authStrats)) throw new Error("Auth strategy must be array");
if (!req.auth)
throw new UnauthorizedError({ name: "Unauthorized access", message: "Token missing" });
@@ -14,4 +14,5 @@ export const verifyAuth =
if (!isAccessAllowed) {
throw new UnauthorizedError({ name: `${req.url} Unauthorized Access` });
}
done();
};
+10 -7
View File
@@ -5,7 +5,6 @@ import { ZodError } from "zod";
import {
BadRequestError,
DatabaseError,
ForbiddenRequestError,
InternalServerError,
UnauthorizedError
} from "@app/lib/errors";
@@ -14,21 +13,25 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
server.setErrorHandler((error, req, res) => {
req.log.error(error);
if (error instanceof BadRequestError) {
res.status(400).send({ statusCode: 400, message: error.message, error: error.name });
void res.status(400).send({ statusCode: 400, message: error.message, error: error.name });
} else if (error instanceof UnauthorizedError) {
res.status(403).send({ statusCode: 403, message: error.message, error: error.name });
void res.status(403).send({ statusCode: 403, message: error.message, error: error.name });
} else if (error instanceof DatabaseError || error instanceof InternalServerError) {
res.status(500).send({ statusCode: 500, message: "Something went wrong", error: error.name });
void res
.status(500)
.send({ statusCode: 500, message: "Something went wrong", error: error.name });
} else if (error instanceof ZodError) {
res.status(403).send({ statusCode: 403, error: "ValidationFailure", message: error.issues });
void res
.status(403)
.send({ statusCode: 403, error: "ValidationFailure", message: error.issues });
} else if (error instanceof ForbiddenError) {
res.status(401).send({
void res.status(401).send({
statusCode: 401,
error: "PermissionDenied",
message: `You are not allowed to ${error.action} on ${error.subjectType}`
});
} else {
res.send(error);
void res.send(error);
}
});
});
@@ -20,17 +20,19 @@ export const registerExternalNextjs = async (
if (standaloneMode) {
const nextJsBuildPath = path.join(dir, "frontend-build");
const { default: conf } = await import(
const { default: conf } = (await import(
path.join(dir, "frontend-build/.next/required-server-files.json"),
// @ts-expect-error type
{
assert: { type: "json" }
}
);
)) as { default: { config: string } };
/* eslint-disable */
const { default: NextServer } = (
await import(path.join(dir, "frontend-build/node_modules/next/dist/server/next-server.js"))
).default;
const nextApp = new NextServer({
dev: false,
dir: nextJsBuildPath,
@@ -52,5 +54,6 @@ export const registerExternalNextjs = async (
});
server.addHook("onClose", () => nextApp.close());
await nextApp.prepare();
/* eslint-enable */
}
};
+5 -3
View File
@@ -1,3 +1,4 @@
import { PushEvent } from "@octokit/webhooks-types";
import { Probot } from "probot";
import SmeeClient from "smee-client";
@@ -22,7 +23,7 @@ export const registerSecretScannerGhApp = async (server: FastifyZodProvider) =>
app.on("push", async (context) => {
const { payload } = context;
await server.services.secretScanning.handleRepoPushEvent(payload as any);
await server.services.secretScanning.handleRepoPushEvent(payload as PushEvent);
});
};
@@ -49,16 +50,17 @@ export const registerSecretScannerGhApp = async (server: FastifyZodProvider) =>
method: "POST",
url: "/",
handler: async (req, res) => {
const eventName = req.headers["x-github-event"] as any;
const eventName = req.headers["x-github-event"];
const signatureSHA256 = req.headers["x-hub-signature-256"] as string;
const id = req.headers["x-github-delivery"] as string;
await probot.webhooks.verifyAndReceive({
id,
// @ts-expect-error type
name: eventName,
payload: req.body as string,
signature: signatureSHA256
});
res.send("ok");
void res.send("ok");
}
});
}
+1 -1
View File
@@ -118,7 +118,7 @@ export const registerRoutes = async (
queue: queueService
}: { db: Knex; smtp: TSmtpService; queue: TQueueServiceFactory }
) => {
server.register(registerSecretScannerGhApp, { prefix: "/ss-webhook" });
await server.register(registerSecretScannerGhApp, { prefix: "/ss-webhook" });
// db layers
const userDAL = userDALFactory(db);
+5 -5
View File
@@ -39,10 +39,10 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
})
}
},
onRequest: (req, _, done) => {
verifyAuth([AuthMode.JWT, AuthMode.API_KEY])(req);
verifySuperAdmin(req);
done();
onRequest: (req, res, done) => {
verifyAuth([AuthMode.JWT, AuthMode.API_KEY])(req, res, () => {
verifySuperAdmin(req, res, done);
});
},
handler: async (req) => {
const config = await server.services.superAdmin.updateServerCfg(req.body);
@@ -97,7 +97,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
}
});
res.setCookie("jid", token.refresh, {
void res.setCookie("jid", token.refresh, {
httpOnly: true,
path: "/",
sameSite: "strict",
+3 -3
View File
@@ -15,8 +15,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
server.route({
url: "/logout",
method: "POST",
config:{
rateLimit:authRateLimit
config: {
rateLimit: authRateLimit
},
schema: {
response: {
@@ -31,7 +31,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
if (req.auth.authMode === AuthMode.JWT) {
await server.services.login.logout(req.permission.id, req.auth.tokenVersionId);
}
res.cookie("jid", "", {
void res.cookie("jid", "", {
httpOnly: true,
path: "/",
sameSite: "strict",
@@ -57,6 +57,7 @@ export const registerIntegrationRouter = async (server: FastifyZodProvider) => {
projectId: integrationAuth.projectId,
event: {
type: EventType.CREATE_INTEGRATION,
// eslint-disable-next-line
metadata: shake({
integrationId: integration.id.toString(),
integration: integration.integration,
@@ -71,6 +72,7 @@ export const registerIntegrationRouter = async (server: FastifyZodProvider) => {
targetServiceId: integration.targetServiceId,
path: integration.path,
region: integration.region
// eslint-disable-next-line
}) as any
}
});
@@ -138,6 +140,7 @@ export const registerIntegrationRouter = async (server: FastifyZodProvider) => {
projectId: integration.projectId,
event: {
type: EventType.DELETE_INTEGRATION,
// eslint-disable-next-line
metadata: shake({
integrationId: integration.id,
integration: integration.integration,
@@ -152,6 +155,7 @@ export const registerIntegrationRouter = async (server: FastifyZodProvider) => {
targetServiceId: integration.targetServiceId,
path: integration.path,
region: integration.region
// eslint-disable-next-line
}) as any
}
});
+12 -12
View File
@@ -12,7 +12,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/srp1",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
schema: {
body: z.object({
@@ -39,7 +39,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/change-password",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
schema: {
body: z.object({
@@ -64,7 +64,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
const appCfg = getConfig();
await server.services.password.changePassword({ ...req.body, userId: req.permission.id });
res.cookie("jid", appCfg.COOKIE_SECRET_SIGN_KEY, {
void res.cookie("jid", appCfg.COOKIE_SECRET_SIGN_KEY, {
httpOnly: true,
path: "/",
sameSite: "strict",
@@ -78,7 +78,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/email/password-reset",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
schema: {
body: z.object({
@@ -103,7 +103,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/email/password-reset-verify",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
schema: {
body: z.object({
@@ -136,7 +136,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "POST",
url: "/backup-private-key",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
@@ -156,10 +156,10 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
const token = validateSignUpAuthorization(req.headers.authorization as string, "",false)!
const token = validateSignUpAuthorization(req.headers.authorization as string, "", false)!;
const backupPrivateKey = await server.services.password.createBackupPrivateKey({
...req.body,
userId: token.userId,
userId: token.userId
});
if (!backupPrivateKey) throw new Error("Failed to create backup key");
@@ -171,7 +171,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
method: "GET",
url: "/backup-private-key",
config: {
rateLimit:passwordRateLimit
rateLimit: passwordRateLimit
},
schema: {
response: {
@@ -182,7 +182,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
const token = validateSignUpAuthorization(req.headers.authorization as string, "",false)!
const token = validateSignUpAuthorization(req.headers.authorization as string, "", false)!;
const backupPrivateKey = await server.services.password.getBackupPrivateKeyOfUser(
token.userId
);
@@ -213,10 +213,10 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
const token = validateSignUpAuthorization(req.headers.authorization as string, "",false)!
const token = validateSignUpAuthorization(req.headers.authorization as string, "", false)!;
await server.services.password.resetPasswordByBackupKey({
...req.body,
userId: token.userId,
userId: token.userId
});
return { message: "Successfully updated backup private key" };
@@ -255,7 +255,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
invitee: UsersSchema,
latestKey: ProjectKeysSchema
latestKey: ProjectKeysSchema.optional()
})
}
},
+14 -1
View File
@@ -1,3 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
// All the any rules are disabled because passport typesense with fastify is really poor
import { Authenticator } from "@fastify/passport";
import fastifySession from "@fastify/session";
import { Strategy as GitHubStrategy } from "passport-github";
@@ -32,6 +40,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
callbackURL: `${appCfg.SITE_URL}/api/v1/sso/google`,
scope: ["profile", " email"]
},
// eslint-disable-next-line
async (req, _accessToken, _refreshToken, profile, cb) => {
try {
const email = profile?.emails?.[0]?.value;
@@ -74,6 +83,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
callbackURL: `${appCfg.SITE_URL}/api/v1/sso/github`,
scope: ["user:email"]
},
// eslint-disable-next-line
async (req, accessToken, _refreshToken, profile, cb) => {
try {
const ghEmails = await fetchGithubEmails(accessToken);
@@ -152,6 +162,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
state: req.query.callback_port,
authInfo: false
// this is due to zod type difference
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any
)(req, res),
handler: () => {}
@@ -165,7 +176,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
failureRedirect: "/login/provider/error",
authInfo: false
// this is due to zod type difference
}) as any,
}) as never,
handler: (req, res) => {
if (req.passportUser.isUserCompleted) {
return res.redirect(
@@ -242,6 +253,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
state: req.query.callback_port,
authInfo: false
// this is due to zod type difference
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any
)(req, res),
handler: () => {}
@@ -255,6 +267,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
failureRedirect: "/login/provider/error",
authInfo: false
// this is due to zod type difference
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any,
handler: (req, res) => {
if (req.passportUser.isUserCompleted) {
@@ -183,7 +183,11 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
querystring: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim().optional(),
secretPath: z.string().trim().optional().transform((val)=> val?removeTrailingSlash(val):val)
secretPath: z
.string()
.trim()
.optional()
.transform((val) => (val ? removeTrailingSlash(val) : val))
}),
response: {
200: z.object({
+2 -2
View File
@@ -19,8 +19,8 @@ export const registerV2Routes = async (server: FastifyZodProvider) => {
);
await server.register(
async (projectServer) => {
projectServer.register(registerProjectRouter);
projectServer.register(registerIdentityProjectRouter);
await projectServer.register(registerProjectRouter);
await projectServer.register(registerIdentityProjectRouter);
},
{ prefix: "/workspace" }
);
+6 -6
View File
@@ -1,8 +1,8 @@
import jwt, { JwtPayload } from "jsonwebtoken";
import jwt from "jsonwebtoken";
import { z } from "zod";
import { getConfig } from "@app/lib/config/env";
import { AuthTokenType } from "@app/services/auth/auth-type";
import { AuthModeMfaJwtTokenPayload, AuthTokenType } from "@app/services/auth/auth-type";
export const registerMfaRouter = async (server: FastifyZodProvider) => {
const cfg = getConfig();
@@ -12,16 +12,16 @@ export const registerMfaRouter = async (server: FastifyZodProvider) => {
const authorizationHeader = req.headers.authorization;
if (!authorizationHeader || !authorizationHeader.startsWith("Bearer ")) {
res.status(401).send({ error: "Missing bearer token" });
void res.status(401).send({ error: "Missing bearer token" });
return res;
}
const token = authorizationHeader.split(" ")[1];
if (!token) {
res.status(401).send({ error: "Missing bearer token" });
void res.status(401).send({ error: "Missing bearer token" });
return res;
}
const decodedToken = jwt.verify(token, cfg.AUTH_SECRET) as JwtPayload;
const decodedToken = jwt.verify(token, cfg.AUTH_SECRET) as AuthModeMfaJwtTokenPayload;
if (decodedToken.authTokenType !== AuthTokenType.MFA_TOKEN)
throw new Error("Unauthorized access");
@@ -79,7 +79,7 @@ export const registerMfaRouter = async (server: FastifyZodProvider) => {
mfaToken: req.body.mfaToken
});
res.setCookie("jid", token.refresh, {
void res.setCookie("jid", token.refresh, {
httpOnly: true,
path: "/",
sameSite: "strict",
@@ -37,7 +37,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
event: {
type: EventType.GET_WORKSPACE_KEY,
metadata: {
keyId: key.id
keyId: key?.id as string
}
}
});
+4 -1
View File
@@ -26,7 +26,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
preHandler: verifyAuth([AuthMode.JWT, AuthMode.API_KEY]),
handler: async (req) => {
const user = await server.services.user.toggleUserMfa(req.permission.id, req.body.isMfaEnabled);
const user = await server.services.user.toggleUserMfa(
req.permission.id,
req.body.isMfaEnabled
);
return { user };
}
});
+1 -1
View File
@@ -81,7 +81,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
return { mfaEnabled: true, token: data.token } as const; // for discriminated union
}
res.setCookie("jid", data.token.refresh, {
void res.setCookie("jid", data.token.refresh, {
httpOnly: true,
path: "/",
sameSite: "strict",
@@ -101,13 +101,13 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
authorization: req.headers.authorization as string
});
server.services.telemetry.sendLoopsEvent(
void server.services.telemetry.sendLoopsEvent(
user.email,
user.firstName || "",
user.lastName || ""
);
server.services.telemetry.sendPostHogEvents({
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.UserSignedUp,
distinctId: user.email,
properties: {
@@ -116,7 +116,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
}
});
res.setCookie("jid", refreshToken, {
await res.setCookie("jid", refreshToken, {
httpOnly: true,
path: "/",
sameSite: "strict",
@@ -168,7 +168,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
userAgent
});
res.setCookie("jid", refreshToken, {
await res.setCookie("jid", refreshToken, {
httpOnly: true,
path: "/",
sameSite: "strict",