Amal Jose commited on
Commit ·
4e83772
1
Parent(s): 7c2ff9b
added files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+13
- .gitignoreAdded+2
- .prettierrcAdded+11
- DockerfileAdded+34
- README.md+5-3
- ecosystem.config.cjsAdded+22
- migrations/create-indexes.tsAdded+118
- package-lock.jsonAdded
- package.jsonAdded+64
- src/app.tsAdded+40
- src/cache/redisCache.tsAdded+64
- src/config/clickhouse.config.tsAdded+14
- src/config/cloud.config.tsAdded+26
- src/config/cookie.config.tsAdded+18
- src/config/cors.config.tsAdded+13
- src/config/email.config.tsAdded+5
- src/config/env.config.tsAdded+72
- src/config/kafka.config.tsAdded+20
- src/config/mongo.config.tsAdded+18
- src/config/oauthStrategies/githubLogin.tsAdded+19
- src/config/oauthStrategies/googleLogin.tsAdded+19
- src/config/oauthStrategies/jwt.tsAdded+27
- src/config/passport.tsAdded+8
- src/config/rate-limiter.config.tsAdded+31
- src/config/redis.config.tsAdded+3
- src/config/stripe.config.tsAdded+3
- src/constants/analytics.tsAdded+6
- src/constants/errors.tsAdded+90
- src/constants/gh.tsAdded+11
- src/constants/paths.tsAdded+13
- src/constants/plan.tsAdded+36
- src/constants/populates/deployment.populate.tsAdded+12
- src/constants/populates/project.populate.tsAdded+46
- src/constants/subdomain.tsAdded+628
- src/constants/types/github.tsAdded+83
- src/controllers/analyticsController.tsAdded+109
- src/controllers/authController.tsAdded+280
- src/controllers/deploymentController.tsAdded+149
- src/controllers/logsController.tsAdded+84
- src/controllers/paymentController.tsAdded+99
- src/controllers/projectController.tsAdded+218
- src/controllers/serverDataOnlyController.tsAdded+19
- src/controllers/webhookController.tsAdded+194
- src/dtos/analytics.dto.tsAdded+9
- src/dtos/auth.dto.tsAdded+24
- src/dtos/deployment.dto.tsAdded+21
- src/dtos/project.dto.tsAdded+131
- src/dtos/zodHelpers.tsAdded+4
- src/events/consumers.tsAdded+82
- src/events/deploymentEmitter.tsAdded+141
12345678910111213# Ignore development filesnode_moduleseslint.config.mjs.dockerignoreDockerfile.env.prettierrc.prettierignoreREADME.mdtestFns.ts# Optionalnpm - debug.log*.log12.envnode_modules1234567891011{ "semi": true, "useTabs": true, "trailingComma": "all", "singleQuote": false, "printWidth": 150, "tabWidth": 4, "bracketSpacing": true, "arrowParens": "always", "endOfLine": "lf"}12345678910111213141516171819202122232425262728293031323334FROM node:20-slim AS builder
RUN mkdir -p /app && chown -R node:node /app
WORKDIR /app
USER node
COPY --chown=node:node package*.json ./RUN npm ci
COPY --chown=node:node . .RUN npm run build
# Stage 2: productionFROM node:20-slimRUN npm install pm2 -gRUN mkdir -p /app && chown -R node:node /appWORKDIR /app
USER node
COPY --chown=node:node package*.json ./ENV NODE_ENV=productionRUN npm ci --omit=dev
COPY --chown=node:node --from=builder /app/dist ./distCOPY --chown=node:node --from=builder /app/ecosystem.config.cjs ./ecosystem.config.cjs
EXPOSE 7860
CMD ["pm2-runtime", "ecosystem.config.cjs"]
123423456789101112---title: Apiemoji: 🌍colorFrom: purpletitle: Server Apiemoji: ⚡colorFrom: yellowcolorTo: graysdk: dockerpinned: falselicense: apache-2.0short_description: No DESC---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122module.exports = { apps: [{ name: "my-express-server", script: "./dist/server.js",
instances: 3, exec_mode: "cluster",
max_memory_restart: "4G",
env: { NODE_ENV: "production", PORT: 7860 // Ensure this matches HF's requirements },
autorestart: true, watch: false, max_restarts: 10, restart_delay: 4000 }]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118/// <reference types="node" />
import connectDB from "../src/config/mongo.config.ts";import { User } from "../src/models/User.ts";import { Project } from "../src/models/Projects.ts";import { Deployment } from "../src/models/Deployment.ts";import { ProjectBandwidth } from "../src/models/ProjectBandwidths.ts";import { OtpModel } from "../src/models/Otp.ts";import mongoose from "mongoose";import "dotenv/config";
async function createIndexes() { try { console.log("Starting index creation...");
console.log("Creating User indexes..."); // await User.collection.createIndex({ email: 1 }, { unique: true, name: "email_unique" }); // await User.collection.createIndex({ stripeCustomerId: 1 }, { sparse: true, name: "stripe_customer_lookup" }); await User.collection.createIndex({ githubInstallationId: 1 }, { sparse: true, name: "github_instalation_id" }); console.log("✓ User indexes created");
//------------------------------------------------------------------------------------------------------------------------------------- console.log("Creating User OTP indexes...");
await OtpModel.collection.createIndex({ userId: 1, purpose: 1 }, { unique: true, name: "otp_user_purpose" }); await OtpModel.collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 60 * 10 }); console.log("✓ User OTP indexes created");
console.log("Creating Project indexes..."); await Project.collection.createIndex( { ghRepoId: 1, user: 1 }, { unique: true, partialFilterExpression: { ghRepoId: { $exists: true } }, name: "github_repo_id_user", }, ); await Project.collection.createIndex({ subdomain: 1 }, { unique: true, name: "subdomain_unique" }); await Project.collection.createIndex({ user: 1, createdAt: -1 }, { name: "user_projects_by_date" }); console.log("✓ Project indexes created"); //------------------------------------------------------------------------------------------------------------------------------------- console.log("Creating Deployment indexes...");
await Deployment.collection.createIndex({ user: 1, project: 1, createdAt: -1 }, { name: "project_deployments_by_date" }); await Deployment.collection.createIndex({ user: 1, createdAt: -1 }, { name: "user_deployments_by_date" }); console.log("✓ Deployment indexes created"); //-------------------------------------------------------------------------------------------------------------------------------------
console.log("Creating ProjectBandwidth indexes..."); await ProjectBandwidth.collection.createIndex({ project: 1, currentMonth: 1 }, { unique: true, name: "project_monthly_bandwidth" }); await ProjectBandwidth.collection.createIndex({ user: 1, currentMonth: 1 }, { name: "user_monthly_bandwidth" }); await ProjectBandwidth.collection.createIndex({ project: 1 }, { name: "project_bandwidth_lookup" }); console.log("✓ ProjectBandwidth indexes created"); //------------------------------------------------------------------------------------------------------------------------------------- console.log("\n✅ All indexes created successfully!"); console.log("\n📋 Index verification:"); const collections = [ { name: "User", model: User }, { name: "Project", model: Project }, { name: "Deployment", model: Deployment }, { name: "ProjectBandwidth", model: ProjectBandwidth }, ];
for (const { name, model } of collections) { const indexes = await model.collection.indexes(); console.log(`\n${name} (${indexes.length} indexes):`); indexes.forEach((idx) => { console.log(` - ${idx.name}: ${JSON.stringify(idx.key)}`); }); } } catch (error) { console.error("❌ Error creating indexes:", error); throw error; }}
async function dropIndexes() { try { console.log("Dropping all custom indexes...");
await User.collection.dropIndexes(); await Project.collection.dropIndexes(); await Deployment.collection.dropIndexes(); await ProjectBandwidth.collection.dropIndexes();
console.log("✅ All custom indexes dropped"); } catch (error) { console.error("❌ Error dropping indexes:", error); throw error; }}
async function main() { const action = process.argv[2];
try { await connectDB(); console.log("📡 Connected to MongoDB\n");
if (action === "down") { await dropIndexes(); } else if (action === "up") { await createIndexes(); }
await mongoose.disconnect(); console.log("\n📡 Disconnected from MongoDB"); process.exit(0); } catch (error) { console.error("Fatal error:", error); await mongoose.disconnect(); process.exit(1); }}
main();
export { createIndexes, dropIndexes };12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "name": "api-server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "clean": "prettier --write .", "build": "tsc && tsc-alias", "start": "node dist/server.js", "dev": "nodemon --exec tsx src/server.ts", "migrate:indexes": "tsx migrations/create-indexes.ts up", "migrate:indexes:down": "tsx migrations/create-indexes.ts down" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "@aws-sdk/client-ecs": "^3.901.0", "@aws-sdk/client-s3": "^3.931.0", "@clickhouse/client": "^1.12.1", "@prisma/client": "^6.16.3", "@types/cookie-parser": "^1.4.9", "bcrypt": "^6.0.0", "cookie-parser": "^1.4.7", "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.1.0", "express-rate-limit": "^8.2.1", "helmet": "^8.1.0", "ioredis": "^5.8.2", "jsonwebtoken": "^9.0.2", "kafkajs": "^2.2.4", "mongoose": "^8.19.0", "morgan": "^1.10.1", "nanoid": "^5.1.6", "passport": "^0.7.0", "passport-github2": "^0.1.12", "passport-google-oauth20": "^2.0.0", "passport-jwt": "^4.0.1", "pm2": "^6.0.14", "random-word-slugs": "^0.1.7", "socket.io": "^4.8.1", "stripe": "^20.0.0", "uuid": "^13.0.0", "winston": "^3.19.0", "zod": "^4.1.11" }, "devDependencies": { "@types/bcrypt": "^6.0.0", "@types/express": "^5.0.3", "@types/jsonwebtoken": "^9.0.10", "@types/morgan": "^1.9.10", "@types/node": "^25.0.1", "@types/passport-github2": "^1.2.9", "@types/passport-google-oauth20": "^2.0.16", "@types/passport-jwt": "^4.0.1", "@types/pg": "^8.15.5", "prettier": "^3.6.2", "tsc-alias": "^1.8.16", "typescript": "^5.9.3" }}12345678910111213141516171819202122232425262728293031323334353637383940import express, { Request } from "express";import { createServer } from "http";import cors from "cors";import cookieParser from "cookie-parser";import passport from "passport";import morgan from "morgan";import helmet from "helmet";
import "./config/passport.js";import connectDB from "./config/mongo.config.js";import { errorHandler } from "./middlewares/globalErrorHandler.js";import { corsOptions } from "./config/cors.config.js";
import { STRIPE_WEBHOOK_REQ_PATH } from "./constants/paths.js";import baseRouter from "./routes/base.route.js";import { apiRouter } from "./routes/index.js";
const app = express();const httpServer = createServer(app);// app.set('trust proxy', true)app.use(cors(corsOptions));
app.use(STRIPE_WEBHOOK_REQ_PATH, express.raw({ type: "application/json" }));
app.use(express.json({ limit: "10mb" }));app.use(express.urlencoded({ extended: true, limit: "10mb" }));app.use(cookieParser());app.use(helmet());app.use(passport.initialize());app.use(morgan("tiny"));
app.set("trust proxy", 1);
app.use("/api", apiRouter);app.use("/", baseRouter);
app.use(errorHandler);
connectDB();export default httpServer;12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { IRedisCache } from "@/interfaces/cache/IRedisCache.js";import { Redis } from "ioredis";
class RedisService implements IRedisCache { private client: Redis; constructor(client: Redis) { this.client = client; }
async get<T>(key: string): Promise<T | null> { const value = await this.client.get(key); return value ? JSON.parse(value) : null; }
async set(key: string, value: unknown, ttlSeconds?: number): Promise<void> { const data = JSON.stringify(value);
if (ttlSeconds) { await this.client.set(key, data, "EX", ttlSeconds); } else { await this.client.set(key, data, "EX", 1800); } }
async del(key: string): Promise<void> { await this.client.del(key); }
async exists(key: string): Promise<boolean> { return (await this.client.exists(key)) === 1; }
async setAdd(key: string, value: string): Promise<number> { return await this.client.sadd(key, value); } async setRemove(key: string, value: string): Promise<number> { return await this.client.srem(key, value); } async getSetLength(key: string): Promise<number> { return await this.client.scard(key); }
async incrementKey(key: string): Promise<number> { return this.client.incr(key); } async decrementKey(key: string): Promise<number> { return this.client.decr(key); } async setKeyExpiry(key: string, time: number): Promise<number> { return this.client.expire(key, time); }
async publishInvalidation(type: string, slug: string): Promise<number> { return this.client.publish("cache:invalidate", JSON.stringify({ type, slug })); } async publishBuild(data: { deploymentId: string; projectId: string; envs: { name: string; value: string }[] }): Promise<number> { return this.client.publish("build:start", JSON.stringify(data)); } async disconnect(): Promise<void> { await this.client.quit(); }}
export default RedisService;1234567891011121314import { createClient } from "@clickhouse/client";import { ENVS } from "@/config/env.config.js";
export const client = createClient({ url: ENVS.CLICKHOUSE_HOST_URL_WITH_PORT as string, //https://wsjhizz301.ap-south-1.aws.clickhouse.cloud:8443 username: ENVS.CLICKHOUSE_USERNAME as string, password: ENVS.CLICKHOUSE_PASSWORD as string, compression: { request: true, response: true, }, max_open_connections: 10,});1234567891011121314151617181920212223242526import { ECSClient } from "@aws-sdk/client-ecs";import { S3Client } from "@aws-sdk/client-s3";import { ENVS } from "@/config/env.config.js";
export const ecsClient = new ECSClient({ region: "us-east-1", credentials: { accessKeyId: ENVS.CLOUD_ACCESSKEY as string, secretAccessKey: ENVS.CLOUD_SECRETKEY as string, },});
export const s3Client = new S3Client({ region: "auto", credentials: { accessKeyId: ENVS.CLOUD_ACCESSKEY as string, secretAccessKey: ENVS.CLOUD_SECRETKEY as string, }, endpoint: ENVS.CLOUD_ENDPOINT, forcePathStyle: true,});
export const config = { CLUSTER: ENVS.CLUSTER_ARN as string, TASK: ENVS.TASK_ARN as string,};123456789101112131415161718import { CookieOptions } from "express";import { ENVS } from "@/config/env.config.js";
const isProd = ENVS.NODE_ENV === "production";
export const accessCookieConfig: CookieOptions = { httpOnly: true, secure: isProd, sameSite: isProd ? "none" : "lax", maxAge: isProd ? 20 * 60 * 1000 : 2 * 60 * 60 * 1000,};
export const refreshCookieConfig: CookieOptions = { httpOnly: true, secure: isProd, sameSite: isProd ? "none" : "lax", maxAge: 24 * 60 * 60 * 1000,};12345678910111213import { CorsOptions } from "cors";import { ENVS } from "@/config/env.config.js";
/** * CORS options used globally in the application. */export const corsOptions: CorsOptions = { origin: ENVS.FRONTEND_URL, methods: ["GET", "POST", "PUT", "PATCH", "DELETE"], allowedHeaders: ["Content-Type", "Authorization", "X-redirect-path"], credentials: true, optionsSuccessStatus: 200, // Needed for legacy browsers};12345import { ENVS } from "@/config/env.config.js";export const EMAIL_SENDER = { name: ENVS.EMAIL_SENDER_NAME, email: ENVS.EMAIL_SENDER_EMAIL,};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import "dotenv/config";import { z } from "zod";import { ZodError } from "zod/v3";
const envSchema = z.object({ MONGO_URL: z.url(), FRONTEND_URL: z.url(), REFRESH_TOKEN_SECRET: z.string(), ACCESS_TOKEN_SECRET: z.string(), PORT: z.coerce.number(), API_ENDPOINT: z.url(), STORAGE_SERVER_ENDPOINT: z.url(),
NODE_ENV: z.string(),
GOOGLE_CLIENT_ID: z.string(), GOOGLE_CLIENT_SECRET: z.string(), GITHUB_CLIENT_ID: z.string(), GITHUB_CLIENT_SECRET: z.string(),
GITHUB_WEBHOOK_SECRET: z.string(), GITHUB_APP_PRIVATE_KEY: z.string().transform((i) => i.replace(/\\n/g, "\n")),
SERVICE_JWT_SECRET: z.string(), CONTAINER_API_TOKEN: z.string(), CONTAINER_NAME: z.string(), SUBNETS_STRING: z.string(), //subnets seperated by comma
CLOUD_ACCESSKEY: z.string(), CLOUD_SECRETKEY: z.string(), CLOUD_ENDPOINT: z.url(),
CLUSTER_ARN: z.string(), TASK_ARN: z.string(), SECURITY_GROUPS: z.string(), // groups seperated by comma CLOUD_BUCKET: z.string(),
KAFKA_USERNAME: z.string(), KAFKA_PASSWORD: z.string(),
CLICKHOUSE_USERNAME: z.string(), CLICKHOUSE_PASSWORD: z.string(), CLICKHOUSE_HOST_URL_WITH_PORT: z.url(),
STRIPE_SECRET_KEY: z.string(), STRIPE_PUBLISHABLE_KEY: z.string(), STRIPE_WEBHOOK_SECRET: z.string(), REDIS_URL: z.url(), BUILD_DISPATCH_PAT_TOKEN: z.string(), BUILD_DISPATCH_URL: z.string(),
VERIFICATION_TOKEN_SECRET: z.string(), OTP_SEND_URL: z.url(), OTP_SEND_API_KEY: z.string(), EMAIL_SENDER_NAME: z.string(), EMAIL_SENDER_EMAIL: z.email(),
NOTIFY_EVENTS_API_KEY: z.string(),});function validateEnv() { try { const envs = envSchema.parse(process.env); console.log("Env validation passed "); return envs; } catch (err) { const error = err as ZodError; console.error(" Environment validation failed:"); console.log(error); process.exit(1); }}export const ENVS = validateEnv();1234567891011121314151617181920import { ENVS } from "@/config/env.config.js";import { Kafka } from "kafkajs";
export const kafka = new Kafka({ clientId: `api-server`, brokers: ["pkc-l7pr2.ap-south-1.aws.confluent.cloud:9092"], ssl: true, sasl: { mechanism: "plain", username: ENVS.KAFKA_USERNAME as string, password: ENVS.KAFKA_PASSWORD as string, }, retry: { retries: 8, restartOnFailure: async () => { process.stdout.write(" ---- kafka retry ---- "); return true; }, },});123456789101112131415161718import { ENVS } from "@/config/env.config.js";import mongoose from "mongoose";
const connectDB = async () => { try { const mongouri = ENVS.MONGO_URL; if (!mongouri) { throw new Error("MONGO_URI not found from .env."); } await mongoose.connect(mongouri); console.log("Database connected"); } catch (error) { console.log(" Database Connection Failed", error); process.exit(1); }};
export default connectDB;12345678910111213141516171819import { PassportStatic } from "passport";import { Strategy as GithubStategy } from "passport-github2";import { githubLoginStrategy } from "../../controllers/authController.js";import { ENVS } from "@/config/env.config.js";
const githubLogin = (passport: PassportStatic) => { passport.use( new GithubStategy( { clientID: ENVS.GITHUB_CLIENT_ID as string, clientSecret: ENVS.GITHUB_CLIENT_SECRET as string, callbackURL: `${ENVS.API_ENDPOINT}/api/auth/github/callback`, }, githubLoginStrategy, ), );};
export default githubLogin;12345678910111213141516171819import { PassportStatic } from "passport";import { Strategy as GoogleStrategy } from "passport-google-oauth20";import { googleLoginStrategy } from "../../controllers/authController.js";import { ENVS } from "@/config/env.config.js";
const googleLogin = (passport: PassportStatic) => { passport.use( new GoogleStrategy( { clientID: ENVS.GOOGLE_CLIENT_ID as string, clientSecret: ENVS.GOOGLE_CLIENT_SECRET as string, callbackURL: `${ENVS.API_ENDPOINT}/api/auth/google/callback`, }, googleLoginStrategy, ), );};
export default googleLogin;123456789101112131415161718192021222324252627import { PassportStatic } from "passport";import { ExtractJwt, Strategy as JWTStrategy } from "passport-jwt";import { ENVS } from "@/config/env.config.js";
const authenticate = (passport: PassportStatic) => { passport.use( new JWTStrategy( { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: ENVS.ACCESS_TOKEN_SECRET as string, }, (jwt_payload, done) => { try { const user = { id: jwt_payload.id, email: jwt_payload.email, name: jwt_payload.name }; if (user) { return done(null, user); } else { return done(null, false); } } catch (error) { return done(error, false); } }, ), );};export default authenticate;12345678import passport from "passport";import googleLogin from "@/config/oauthStrategies/googleLogin.js";import githubLogin from "@/config/oauthStrategies/githubLogin.js";import authenticate from "@/config/oauthStrategies/jwt.js";googleLogin(passport);githubLogin(passport);
authenticate(passport);12345678910111213141516171819202122232425262728293031import { COMMON_ERRORS } from "@/constants/errors.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { Options } from "express-rate-limit";const baseRateLimitConfig: Partial<Options> = { standardHeaders: true, legacyHeaders: false, handler: (req, res) => { res.status(STATUS_CODES.TOO_MANY_REQUESTS).json({ success: false, message: COMMON_ERRORS.RATE_LIMIT_EXCEEDED, }); },};
export const defaultLimiter: Partial<Options> = { windowMs: 1 * 60 * 1000, max: 100, ...baseRateLimitConfig,};
export const analyticsLimiter: Partial<Options> = { windowMs: 1 * 60 * 1000, max: 20, ...baseRateLimitConfig,};
export const logsLimiter: Partial<Options> = { windowMs: 1 * 60 * 1000, max: 40, ...baseRateLimitConfig,};123import { ENVS } from "@/config/env.config.js";import { Redis } from "ioredis";export const redisClient = new Redis((ENVS.REDIS_URL as string) || "");123import { ENVS } from "@/config/env.config.js";import Stripe from "stripe";export const stripe = new Stripe(ENVS.STRIPE_SECRET_KEY as string);123456export const FREE_ALLOWED_COMBINATIONS = [ { interval: 1, intervalUnit: "HOUR", range: 1, rangeUnit: "HOUR" }, { interval: 1, intervalUnit: "HOUR", range: 24, rangeUnit: "HOUR" }, { interval: 1, intervalUnit: "DAY", range: 7, rangeUnit: "DAY" }, { interval: 1, intervalUnit: "DAY", range: 30, rangeUnit: "DAY" },] as const;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990export const USER_ERRORS = { NOT_FOUND: "User not found", ALREADY_EXISTS: "Email already exists", INVALID_CREDENTIALS: "Invalid email or password", UNAUTHORIZED: "Unauthorized access", ACCOUNT_LOCKED: "Account temporarily locked. Try again later", FORBIDDEN: "You do not have permission to perform this action", EMAIL_REQUIRED: "Email is required", EMAIL_NOT_VERIFIED: "Please verify your email before logging in", INVALID_TOKEN: "Invalid or expired token", NO_TOKEN: "Token not found", LOGIN_REQUIRED: "Login required", NOT_AUTHENTICATED: "User not authenticated", CALLBACK_ERROR: "Error during google callback", CREATION_ERROR: "Error on user sign up", REFRESH_TOKEN_EXPIRED: "Refresh token expired",};
export const PROJECT_ERRORS = { INCOMPLETE_DATA: "Submitted data is incomplete", NOT_FOUND: "Project not found", CREATE_FAILED: "Failed to create project", UPDATE_FAILED: "Failed to update project", DELETE_FAILED: "Failed to delete project", LIMIT_REACHED: "Project limit reached for your account", IN_USE: "Cannot delete project while it has active deployments", PROJECT_IN_PROGRESS: "Project deployment in progress", SUBDOMAIN_NOT_AVAILABLE: "Subdomain not available", DISABLED: "Project disabled",};
export const DEPLOYMENT_ERRORS = { NOT_FOUND: "Deployment not found", CREATE_FAILED: "Failed to create deployment", UPDATE_FAILED: "Failed to update deployment", DELETE_FAILED: "Failed to delete deployment", DEPLOY_FAILED: "Deployment process failed", NO_ACTIVE_DEPLOYMENT: "No active deployment found", CONCURRENT_LIMIT: "Maximum concurrent deployments for user reached", DAILY_DEPLOYMENT_LIMIT: "Daily deployment limit exceeded", BUSY_RUNNERS: "Busy Runners. Please try again later", ALREADY_ACTIVE: "Deployment already active", NOT_RELATED: "This deployment does not belong to the selected project", CANT_MAKE_ACTIVE: (status: string) => `Only successful deployments can be activated. Current status: ${status}.`,};
export const PAYMENT_ERRORS = { NOT_FOUND: "Payment record not found", FAILED: "Payment processing failed", SUBSCRIPTION_CANCELLED: "Subscription has been cancelled", NO_ACTION_TAKEN: "No action taken",};
export const OTP_ERRORS = { GENERATION_FAILED: "Failed to generate OTP", SEND_FAILED: "Failed to send OTP", INVALID_OTP: "Invalid OTP code", EXPIRED: "OTP has expired", NOT_FOUND: "OTP not found or expired", RESEND_LIMIT: "Too many OTP requests, please try again later", VERIFICATION_FAILED: "OTP verification failed", MAX_ATTEMPTS: (attempts: number) => `Maximum ${attempts} attempts exceeded`, COOLDOWN_ACTIVE: (seconds: number) => `Please wait ${seconds} seconds before requesting a new OTP`,};
export const COMMON_ERRORS = { INTERNAL_SERVER: "Internal server error", SOMETHING_WENT_WRONG: "Error; Something went wrong", INVALID_ID: (id: string) => "Invalid ID === > " + id, VALIDATION_ERRORS: (messages: string, source: string) => `${source} validation error => ${messages}`, RATE_LIMIT_EXCEEDED: "Too many requests; please try again later", COOKIE_NOT_PROVIDED: "No auth cookie provided", TOKEN_VALIDATION: "Error during token valiadation", NOT_FOUND: "Not found",};
export const WEBHOOK_ERRORS = { USER_NOT_FOUND: "Requested user not found ", INCOMPLETE_DATA: "Can't find user data from Github ", UNINSTALL_ERROR: "Error on uninstalling Github App due ", INCOMPLE_DATA: "Incomplete data for installation request ", SIGNATURE_INVALID: "Invalid Secret or Signature", SIGNATURE_DECODE_ERROR: "Error while parsing signature", SIGNATURE_NOT_FOUND: "Signature not found", ALREDY_CONNECTED: "Already connected to an account. Please remove it first", ACCESS_TOKEN_CREATE_ERROR: "Error while creating access token", REPO_FETCH: "Error fetching repositories", BRANCH_FETCH: "Error fetching repository branches", NOT_CONNECTED: "Github app not connected",};1234567891011export const githubAppSlug = "lynfera-app";export const githubAppId = 2973065;
export const installationIdVerifyUrl = "https://api.github.com/app/installations/";export const newAccessTokensUrl = (id: number) => `https://api.github.com/app/installations/${id}/access_tokens`;
export const reposUrl = "https://api.github.com/installation/repositories";export const makeRepoUr = (owner: string, repo: string) => `https://api.github.com/repos/${owner}/${repo}`;export const makeRepoBranchUr = (owner: string, repo: string) => `https://api.github.com/repos/${owner}/${repo}/branches`;
export const GITHUB_ACCEPT_HEADER = "application/vnd.github+json";12345678910111213export const LOCAL_TEST_SERVER_PATH = "../test-server";export const LOCAL_TEST_SERVER_USER_FILES = "../test-server/public/user-projects";
export const BUILD_SERVER_PATH = "../build-server/";export const BUILD_SERVER_RUN_SCRIPT = "script.js";
export const S3_OUTPUTS_DIR = "__app_build_outputs";
export const FRONTEND_REDIRECT_PATH = "/auth/success";export const FRONTEND_PAYMENT_CANCEL_PATH = "/projects";export const FRONTEND_PAYMENT_SUCCESS_PATH = "/payment-success?session_id=";
export const STRIPE_WEBHOOK_REQ_PATH = "/api/billing/stripe-webhook";123456789101112131415161718192021222324252627282930313233343536type EachPlanFields = { name: string; slug: string; pricePerMonth: number; maxProjects: number; concurrentBuilds: number; maxDailyDeployments: number; totalBandwidthGB: number; features?: string[];};export interface IPlans { FREE: EachPlanFields; PRO: EachPlanFields;}export const PLANS: IPlans = { FREE: { name: "FREE", slug: "Starter", pricePerMonth: 0, maxProjects: 10, concurrentBuilds: 1, maxDailyDeployments: 18, totalBandwidthGB: 15, features: [], // call as function }, PRO: { name: "PRO", slug: "Pro", pricePerMonth: 5, maxProjects: 30, concurrentBuilds: 3, maxDailyDeployments: 40, totalBandwidthGB: 80, features: [], // call as function },} as const;123456789101112export const DEPLOYMENT_POPULATE_MAP = { user: { path: "user", select: "name email profileImage", }, project: { path: "project", select: "name branch subdomain repoURL currentDeployment", },} as const;
export const deploymentBasicFields = ["_id", "project", "commit_hash", "publicId", "status", "identifierSlug"];12345678910111213141516171819202122232425262728293031323334353637383940414243444546export const PROJECT_POPULATE_MAP = { user: { path: "user", select: "name email profileImage", }, deployments: { path: "deployments", select: "status createdAt", },} as const;
export const projectBasicFields = [ "name", "branch", "repoURL", "techStack", "status", "currentDeployment", "tempDeployment", "lastDeployment", "subdomain", "user", "deployments", "lastDeployedAt", "createdAt",];
export const projectSettingsFields = [ "_id", "name", "branch", "repoURL", "status", "subdomain", "user", "createdAt", "buildCommand", "env", "outputDirectory", "rootDir", "isDisabled", "isDeleted", "rewriteNonFilePaths",];
export const projectUpdateFieldsString = ["name", "_id"];123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628export const DEPLOYMENT_ID_LENGTH = 10;export const DEPLOYMENT_SEPARATOR_LENGTH = 4;export const MAX_SUBDOMAIN_LENGTH = 61;
export const BRAND_PROTECTION_REGEX = /\blynf[eia]?r[eao]?[a-z0-9-]*/i;
export const RESERVED_SUBDOMAINS = new Set([ "app", "dashboard", "console", "panel", "system", "status", "health", "metrics", "monitor", "logs", "account", "accounts", "user", "users", "profile", "settings", "security", "verify", "verification", "reset", "password", "oauth", "sso", "portal", "home", "main", "official", "platform", "core", "base", "hub", "invite", "join", "member", "members", "vip", "premium", "pro", "plus",
"api", "cdn", "assets", "static", "files", "media", "img", "css", "lib", "dev", "develop", "developer", "developers", "staging", "stage", "preview", "test", "testing", "sandbox", "demo", "example", "examples", "lab", "labs", "ns1", "ns2", "dns", "proxy", "gateway", "tunnel", "git", "svn", "ssh", "cluster", "node", "k8s", "docker", "registry", "vault", "secret", "secrets", "config", "deploy", "build", "cicd", "lambda", "serverless", "hook", "hooks",
"admin", "administrator", "root", "master", "default", "global", "sudo", "auth", "login", "logout", "signin", "signup", "register", "internal", "ops", "devops", "security", "exploit", "hacker", "phish", "malware", "virus", "bypass", "crack", "null", "undefined", "void", "anon", "anonymous",
"billing", "bill", "payments", "pay", "checkout", "pricing", "plans", "plan", "invoice", "invoices", "subscription", "subscriptions", "refund", "tax", "legal", "tos", "privacy", "abuse", "compliance", "terms", "policy", "well-known", "report", "trust", "claim", "partner", "affiliate", "reseller", "enterprise", "corp", "venture", "sales", "promo", "deal", "offer",
"help", "support", "contact", "ticket", "wiki", "docs", "learn", "guide", "blog", "news", "press", "community", "jobs", "careers", "marketing", "shop", "store", "cart", "search", "video", "images", "forum", "chat", "feed", "stream", "live", "social", "robots", "sitemap", "crawler", "spider",
"mail", "email", "smtp", "imap", "pop", "webmail", "ftp", "mta", "relay", "www", "www2", "host", "localhost", "broadcast", "webmaster", "postmaster",
"google", "bing", "yahoo", "facebook", "meta", "twitter", "discord", "github", "gitlab", "bitbucket", "vercel", "netlify", "cloudflare", "aws", "azure", "heroku", "digitalocean", "supabase", "firebase", "apple", "icloud", "microsoft",]);
export const ADDITIONAL_RESERVED_SUBDOMAINS = new Set([ "backup", "backups", "archive", "archives", "cache", "redis", "memcache", "database", "postgres", "mysql", "mongo", "elasticsearch", "elastic", "queue", "worker", "workers", "cron", "scheduler", "task", "tasks", "websocket", "wss", "socket", "sockets", "realtime", "storage", "bucket", "blob", "object", "artifacts", "artifact", "edge", "origin", "balancer", "firewall", "waf", "ddos", "ipv4", "ipv6", "tcp", "udp", "http", "https", "ssl", "tls", "cert", "endpoint", "endpoints", "graphql", "rest", "grpc", "webhook", "webhooks",
"analytics", "stats", "statistics", "tracking", "track", "trace", "tracing", "sentry", "bugsnag", "datadog", "newrelic", "grafana", "prometheus", "alert", "alerts", "notification", "notifications", "notify", "incident", "uptime", "downtime", "performance", "perf", "speed", "benchmark", "audit", "audits", "telemetry", "observability", "apm",
"production", "prod", "preprod", "pre-prod", "uat", "canary", "blue", "green", "rollback", "release", "releases", "version", "alpha", "beta", "stable", "latest", "edge-deploy",
"identity", "idp", "saml", "ldap", "okta", "auth0", "cognito", "session", "sessions", "token", "tokens", "jwt", "refresh", "access", "permission", "permissions", "role", "roles", "group", "groups", "team", "teams", "org", "organization", "organizations", "tenant", "tenants", "workspace", "invite-user", "onboard", "onboarding", "offboard",
"order", "orders", "customer", "customers", "client", "clients", "vendor", "purchase", "transaction", "transactions", "wallet", "balance", "credit", "discount", "coupon", "coupons", "voucher", "vouchers", "gift", "giftcard", "product", "products", "catalog", "inventory", "quote", "quotes",
"upload", "uploads", "download", "downloads", "share", "sharing", "public", "private", "draft", "drafts", "publish", "editor", "edit", "preview-app", "comment", "comments", "review", "reviews", "rating", "ratings", "feedback", "message", "messages", "inbox", "outbox", "notification-center", "alert-center", "newsletter", "subscribe", "unsubscribe", "campaign", "campaigns",
"documentation", "doc", "readme", "changelog", "release-notes", "api-docs", "reference", "tutorial", "tutorials", "workshop", "training", "course", "academy", "university", "edu", "education", "knowledge", "faq",
"gdpr", "ccpa", "hipaa", "pci", "soc2", "iso", "compliance-report", "vulnerability", "cve", "security-txt", "pgp", "gpg", "keybase", "audit-log", "access-log", "activity", "consent", "cookie", "cookies", "dpo", "dmca", "copyright", "trademark", "patent", "ip-rights",
"127-0-0-1", "0-0-0-0", "loopback", "local", "internal-api", "private-api", "protected", "restricted", "blacklist", "whitelist", "allowlist", "denylist", "quarantine", "blocked",
"status-page", "ping", "healthcheck", "readiness", "liveness", "probe", "service", "services", "microservice", "function", "functions", "lambda-fn", "event", "events", "stream-api", "pub", "sub", "pubsub", "mqtt", "amqp",
"warehouse", "datawarehouse", "datalake", "etl", "pipeline", "pipelines", "business-intelligence", "reports", "dashboard-analytics", "insight", "insights", "metric", "kpi", "visualization", "chart", "charts",
"integration", "integrations", "connector", "connectors", "plugin", "plugins", "extension", "extensions", "addon", "addons", "app-store", "marketplace", "zapier", "ifttt", "n8n", "make", "integromat", "automation", "workflow",
"mobile", "ios", "android", "app-download", "apk", "ipa", "testflight", "play", "appstore", "native", "hybrid", "pwa", "electron", "desktop",
"abuse-report", "spam", "fraud", "scam", "fake", "impersonate", "clone", "mirror", "copy", "replica", "backup-mirror", "test-user", "dummy", "placeholder", "reserved", "blocked-user", "suspended", "banned", "deleted",
"rss", "atom", "feed-rss", "amp", "manifest", "service-worker", "opensearch", "humans", "ads", "adsense", "adserver", "advertising",
"i18n", "l10n", "locale", "locales", "lang", "language", "translate", "translation", "asia", "apac", "emea",
"sandbox-user", "staging-user", "test-account", "demo-account", "guest", "trial", "free", "starter", "professional", "business", "unlimited", "coming-soon", "under-construction", "maintenance", "offline", "emergency",]);1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283export type GithubRepoResponse = { id: number; node_id: string; name: string; full_name: string; private: boolean;
owner: GithubRepositoryOwner;
html_url: string; description: string | null; fork: boolean;
url: string;
created_at: string; updated_at: string; pushed_at: string;
git_url: string; ssh_url: string; clone_url: string;
default_branch: string;
visibility: "public" | "private" | "internal";
forks_count: number; stargazers_count: number; watchers_count: number;
open_issues_count: number;
language: string | null;
archived: boolean; disabled: boolean;
permissions?: GithubRepositoryPermissions;};type commitInnerUser = { name: string; email: string; date: string; username: string;};export interface GithubCommitType { id: string; message: string; timestamp: string; url: string; author: commitInnerUser; committer: commitInnerUser; added: string[]; removed: string[]; modified: string[];}export interface GithubRepositoryOwner { login: string; id: number; node_id: string; avatar_url: string; html_url: string; type: "User" | "Organization"; site_admin: boolean;}
export interface GithubRepositoryPermissions { admin: boolean; maintain?: boolean; push: boolean; triage?: boolean; pull: boolean;}
export interface GithubRepositoryBranch { name: string; commit: { sha: string; url: string; }; protected: boolean;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import { AnalyticsQueryDTO } from "@/dtos/analytics.dto.js";import { IAnalyticsController } from "@/interfaces/controller/IAnalyticsController.js";import { IAnalyticsService } from "@/interfaces/service/IAnalyticsService.js";import { AnalyticsMapper } from "@/mappers/AnalyticsMapper.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { Request, Response, NextFunction } from "express";
class AnalyticsController implements IAnalyticsController { private analyticsService: IAnalyticsService;
constructor(analyticsService: IAnalyticsService) { this.analyticsService = analyticsService; } async clearAnalytics(req: Request, res: Response, next: NextFunction): Promise<void> { try { const { projectId } = req.params; await this.analyticsService.clearAnalytics(projectId); res.status(STATUS_CODES.NO_CONTENT).json({ ok: true }); } catch (error) { next(error); } } async bandWidth(req: Request, res: Response, next: NextFunction): Promise<void> { const { projectId } = req.params; const { range, interval, limit } = req.validatedQuery as AnalyticsQueryDTO; const userPlan = req.user?.plan as string;
try { const [data, queryOptions] = await this.analyticsService.getBandwidthData(projectId, userPlan, { range: range as string, interval: interval as string, }); const response = AnalyticsMapper.bandwidthResponseDTO(data, projectId, queryOptions);
res.json(response); return; } catch (error) { next(error); } } async overview(req: Request, res: Response, next: NextFunction): Promise<void> { const { projectId } = req.params; const { range, interval } = req.validatedQuery as AnalyticsQueryDTO; const userPlan = req.user?.plan as string; try { const [data, queryOptions] = await this.analyticsService.getOverView(projectId, userPlan, { range: range as string, interval: interval as string, }); const response = AnalyticsMapper.overviewResponse(data, projectId, queryOptions);
res.json(response); return; } catch (error) { next(error); } } async realtime(req: Request, res: Response, next: NextFunction): Promise<void> { const { projectId } = req.params; const { interval } = req.validatedQuery as AnalyticsQueryDTO;
try { const [data, queryOptions] = await this.analyticsService.getRealtime(projectId, { interval: interval as string }); const response = AnalyticsMapper.realtimeResponse(data, projectId, queryOptions);
res.json(response); return; } catch (error) { next(error); } } async topPages(req: Request, res: Response, next: NextFunction): Promise<void> { const { projectId } = req.params; const { range, limit } = req.validatedQuery as AnalyticsQueryDTO; const userPlan = req.user?.plan as string; try { const [data, queryOptions] = await this.analyticsService.getTopPages(projectId, userPlan, { range: range as string, limit: Number(limit || 30), }); const response = AnalyticsMapper.topPagesResponse(data, projectId, queryOptions);
res.json(response); return; } catch (error) { next(error); } } async platformStats(req: Request, res: Response, next: NextFunction): Promise<void> { const { projectId } = req.params; const { range, limit } = req.validatedQuery as AnalyticsQueryDTO; const userPlan = req.user?.plan as string;
try { const [data, queryOptions] = await this.analyticsService.getPlatformStats(projectId, userPlan, { range: range as string, limit: Number(limit || 30), }); const response = AnalyticsMapper.platformResponse(data, projectId, queryOptions);
res.json(response); return; } catch (error) { next(error); } }}
export default AnalyticsController;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import { NextFunction, Request, Response } from "express";import { Profile, VerifyCallback } from "passport-google-oauth20";import jwt from "jsonwebtoken";
import { ENVS } from "@/config/env.config.js";import AppError from "@/utils/AppError.js";import { issueAuthAccessCookies, issueAuthRefreshCookies, issueOtherCookies } from "@/utils/authUtils.js";import { userService } from "@/instances.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { UserMapper } from "@/mappers/userMapper.js";import { LoginUserDTO, SignUpUserDTO, VerifyOtpDTO } from "@/dtos/auth.dto.js";import { generateOtpToken, RefresheTokenType } from "@/utils/generateToken.js";import { accessCookieConfig, refreshCookieConfig } from "@/config/cookie.config.js";import { COMMON_ERRORS, OTP_ERRORS, USER_ERRORS } from "@/constants/errors.js";import { FRONTEND_REDIRECT_PATH } from "@/constants/paths.js";import { notify } from "@/utils/notifyOnSignup.js";
const OTP_COOKIE = "otp_Cookie";
export const oAuthLoginCallback = (req: Request, res: Response, next: NextFunction) => { try { if (!req.user) { return next(new AppError(USER_ERRORS.NOT_AUTHENTICATED, STATUS_CODES.UNAUTHORIZED)); } issueAuthAccessCookies(res, { id: req.user.id, plan: req.user.plan }); issueAuthRefreshCookies(res, { id: req.user.id, plan: req.user.plan }, { currentRefresh: 0, originalIssuedAt: Date.now() }); issueOtherCookies(res); const frontend = ENVS.FRONTEND_URL + FRONTEND_REDIRECT_PATH + ((req.user as any).newUser ? "?newuser=true" : ""); // console.log({ frontend, user: req.user }) if ((req.user as any).newUser) { notify( (req.user as any).nameString.split("%-%")[0], (req.user as any).nameString.split("%-%")[1], req.socket.remoteAddress || req.ip || "", ); } res.redirect(frontend); } catch (error) { next(new AppError(USER_ERRORS.CALLBACK_ERROR, STATUS_CODES.INTERNAL_SERVER_ERROR, error)); }};
export const googleLoginStrategy = async (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => { console.log("strategy google"); try { const { user, newUser } = await userService.googleLoginStrategy(profile); const doneUser = { id: user._id, plan: user.plan, newUser, nameString: `${user.name}%-%${user.email}`, }; done(null, doneUser); } catch (error) { done(error, false); }};
export const githubLoginStrategy = async (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => { try { console.log("strategy github"); const { user, newUser } = await userService.githubLoginStrategy(profile); const doneUser = { id: user._id, plan: user.plan, newUser, }; done(null, doneUser); } catch (error) { done(error, false); }};
export const refresh = async (req: Request, res: Response, next: NextFunction) => { const refreshToken = req.cookies.refresh_token; if (!refreshToken) { console.log("No refresh token"); res.status(STATUS_CODES.UNAUTHORIZED).json({ message: COMMON_ERRORS.COOKIE_NOT_PROVIDED }); return; } try { const decoded = jwt.verify(refreshToken, ENVS.REFRESH_TOKEN_SECRET as string) as RefresheTokenType;
console.log("Trying to decode refesh", decoded); const user = await userService.getUser(decoded.id); if (!user) { throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND); }
const expiresAt = (decoded.exp as number) * 1000; const now = Date.now(); const hoursLeft = (expiresAt - now) / (1000 * 60 * 60);
if (hoursLeft < 6 && hoursLeft > 0) { console.log("refreshing refresh token also"); issueAuthRefreshCookies( res, { id: user._id, plan: user.plan }, { currentRefresh: decoded.crntRfrshCount + 1, originalIssuedAt: decoded.oIAT }, ); } issueAuthAccessCookies(res, { id: user._id, plan: user.plan }); issueOtherCookies(res); return res.status(STATUS_CODES.OK).json({ ok: true }); } catch (error) { if (error instanceof AppError) { next(error); return; } if (error instanceof Error) { if (error.name === "TokenExpiredError") { next(new AppError(USER_ERRORS.REFRESH_TOKEN_EXPIRED, STATUS_CODES.UNAUTHORIZED, error)); return; }
if (error.name === "JsonWebTokenError") { next(new AppError(USER_ERRORS.INVALID_TOKEN, STATUS_CODES.UNAUTHORIZED, error)); return; } } next(new AppError(COMMON_ERRORS.TOKEN_VALIDATION, STATUS_CODES.INTERNAL_SERVER_ERROR, error)); console.log("Error in token valiadation "); }};
export const checkAuth = (req: Request, res: Response, next: NextFunction) => { return res.status(STATUS_CODES.OK).json({ ok: true, randomNumber: Math.floor(Math.random() * 1000) });};
export const verifyAuth = (req: Request, res: Response) => { return res.status(STATUS_CODES.OK).json({ valid: true, user: req.user });};
export const userLogout = (req: Request, res: Response) => { res.clearCookie("refresh_token", refreshCookieConfig); res.clearCookie("access_token", accessCookieConfig); res.clearCookie("is_Authenticated"); res.status(STATUS_CODES.OK).json({ message: "user logged out" });};
export const getAuthenticatedUser = async (req: Request, res: Response, next: NextFunction) => { try { const userId = req.user?.id as string; const user = await userService.getUser(userId); if (!user) { res.status(STATUS_CODES.NOT_FOUND).json({ error: USER_ERRORS.NOT_AUTHENTICATED, message: USER_ERRORS.NOT_FOUND, }); return; } const response = UserMapper.toUserResponse(user); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); }};
export const signUpUser = async (req: Request, res: Response, next: NextFunction) => { try { const userData = req.validatedBody as SignUpUserDTO; const result = await userService.signUpUser(userData);
if (!result) { res.status(STATUS_CODES.BAD_REQUEST).json({ error: USER_ERRORS.CREATION_ERROR }); return; } const user = result.user; const otpSent = result.otpResult; const response = UserMapper.toUserResponse(user); res.cookie(OTP_COOKIE, generateOtpToken(response.user._id), { ...accessCookieConfig }); res.status(STATUS_CODES.CREATED).json({ message: "OTP Sent", otpSent, user: response.user }); } catch (error) { next(error); }};
export const loginUser = async (req: Request, res: Response, next: NextFunction) => { try { const userData = req.validatedBody as LoginUserDTO; const user = await userService.loginUser(userData); if (user) { const response = UserMapper.toUserResponse(user); if (!user.isVerified) { res.cookie(OTP_COOKIE, generateOtpToken(response.user._id), { ...accessCookieConfig }); res.status(STATUS_CODES.FORBIDDEN).json({ message: USER_ERRORS.EMAIL_NOT_VERIFIED, requiresOtpVerification: true, loginSuccess: false, }); return; } issueAuthAccessCookies(res, { id: response.user._id, plan: response.user.plan }); issueAuthRefreshCookies(res, { id: response.user._id, plan: response.user.plan }, { currentRefresh: 0, originalIssuedAt: Date.now() }); issueOtherCookies(res); res.status(STATUS_CODES.OK).json({ loginSuccess: true, user: response.user }); return; } res.status(STATUS_CODES.NOT_FOUND).json({ message: USER_ERRORS.NOT_FOUND, statusCode: 404 }); return; } catch (error) { next(error); }};
export const verifyOtp = async (req: Request, res: Response, next: NextFunction) => { try { const userData = req.validatedBody as VerifyOtpDTO; const result = await userService.verifyUserOtp(userData.email, userData.otp); if (result.verifyResult) { const { user } = result; if (user) { const response = UserMapper.toUserResponse(user); issueAuthAccessCookies(res, { id: response.user._id, plan: response.user.plan }); issueAuthRefreshCookies( res, { id: response.user._id, plan: response.user.plan }, { currentRefresh: 0, originalIssuedAt: Date.now() }, ); issueOtherCookies(res); res.clearCookie(OTP_COOKIE); res.status(STATUS_CODES.OK).json({ message: "OTP Verified succesfully", user: response.user }); notify(user.name, user.email, req.socket.remoteAddress || req.ip || ""); return; } } res.status(STATUS_CODES.BAD_REQUEST).json({ message: OTP_ERRORS.VERIFICATION_FAILED, statusCode: STATUS_CODES.BAD_REQUEST, }); } catch (error) { next(error); }};
export const resendOtp = async (req: Request, res: Response, next: NextFunction) => { try { const otpCookie = req.cookies.otp_Cookie; if (!otpCookie) { res.status(STATUS_CODES.BAD_REQUEST).json({ message: "Cant send otp, insufficient data" }); return; } const decoded = jwt.verify(otpCookie, ENVS.VERIFICATION_TOKEN_SECRET as string) as { id: string }; const { id } = decoded;
const result = await userService.resentOtp(id || "---"); res.status(STATUS_CODES.OK).json({ message: "OTP Sent", otpsent: result }); } catch (error) { next(error); }};
export const getAuthenticatedUserDetails = async (req: Request, res: Response, next: NextFunction) => { try { const userId = req.user?.id as string; const { user, bandwidth } = await userService.getUserDetailed(userId); if (!user) { res.status(STATUS_CODES.NOT_FOUND).json({ error: USER_ERRORS.NOT_FOUND }); return; } const response = UserMapper.toUserDetailedResponse({ user, bandwidth }); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); }};export const getUserGthbInstallationInfo = async (req: Request, res: Response, next: NextFunction) => { try { const userId = req.user?.id as string; const result = await userService.getGithubInstallationInfo(userId); if (!result) { res.status(STATUS_CODES.OK).json({ error: COMMON_ERRORS.NOT_FOUND }); return; } const response = UserMapper.toUserInstallationResponse(result, userId); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); }};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import { Request, Response, NextFunction } from "express";
import { IDeploymentController } from "@/interfaces/controller/IDeploymentController.js";import { IDeploymentService } from "@/interfaces/service/IDeploymentService.js";import { DeploymentMapper } from "@/mappers/DeploymentMapper.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { QueryDeploymentDTO } from "@/dtos/deployment.dto.js";import { COMMON_ERRORS } from "@/constants/errors.js";
class DeploymentController implements IDeploymentController { private deploymentService: IDeploymentService; constructor(deployService: IDeploymentService) { this.deploymentService = deployService; }
async createDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { const userId = req.user?.id as string; const projectId = req.params.projectId; const isRedeploy = req.body.isRedeploy; try { const deployment = await this.deploymentService.newDeployment({}, userId, projectId, isRedeploy);
if (!deployment) { res.status(STATUS_CODES.BAD_REQUEST).json({ deployment: null }); return; } const response = DeploymentMapper.toDeploymentFullResponse(deployment); res.status(STATUS_CODES.CREATED).json(response); } catch (error) { next(error); } }
async getDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const deploymentId = req.params.deploymentId; const includesField = req.query.include as string;
const result = await this.deploymentService.getDeploymentById(deploymentId, userId, includesField); if (result) { const response = DeploymentMapper.toDeploymentFullResponse(result); res.status(STATUS_CODES.OK).json(response); return; } res.status(STATUS_CODES.NOT_FOUND).json({ deployment: null }); } catch (error) { next(error); } }
async getDeploymentsByProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const query = req.validatedQuery as QueryDeploymentDTO;
const projectId = req.params.projectId;
const result = await this.deploymentService.getProjectDeployments(userId, projectId, query); const response = DeploymentMapper.toDeployments( result.deployments, { total: result.total, page: query.page, limit: query.limit, }, query.full ? "full" : "overview", ); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } }
async getDeploymentFilesData(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const deploymentId = req.params.deploymentId;
const result = await this.deploymentService.getDeploymentFiles(deploymentId, userId); if (!result) { res.status(STATUS_CODES.NOT_FOUND).json({ status: 404, error: "not_found", message: COMMON_ERRORS.NOT_FOUND, }); return; } const response = DeploymentMapper.toDeploymentFilesResponse(result); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } } async getAllDeployments(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const query = req.validatedQuery as QueryDeploymentDTO;
const result = await this.deploymentService.getAllDeployments(userId, query); const response = DeploymentMapper.toDeployments( result.deployments, { total: result.total, page: query.page, limit: query.limit, }, query.full ? "full" : "overview", ); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } }
async deleteDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { try { const deploymentId = req.params.deploymentId; const projectId = req.params.projectId;
const result = await this.deploymentService.deleteDeployment(projectId, deploymentId, req.user?.id as string); if (result !== 0) { res.status(STATUS_CODES.NO_CONTENT).json({ deleted: true }); return; } res.status(STATUS_CODES.NO_CONTENT).json({}); } catch (error) { next(error); } }
async __getDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { try { const deploymentId = req.params.id; const deployment = await this.deploymentService.__getDeploymentById(deploymentId); if (deployment) { const response = DeploymentMapper.toDeploymentFullResponse(deployment); res.status(STATUS_CODES.OK).json(response); return; } res.status(STATUS_CODES.NOT_FOUND).json({ deployment: null }); console.log("not found"); } catch (error) { next(error); } }}
export default DeploymentController;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { Request, Response, NextFunction } from "express";import { v4 } from "uuid";
import { ILogsController } from "@/interfaces/controller/ILogsController.js";import { ILogsService } from "@/interfaces/service/ILogsService.js";import { LogMapper } from "@/mappers/LogsMapper.js";import { sseManager } from "@/events/deploymentEmitter.js";import { IDeploymentService } from "@/interfaces/service/IDeploymentService.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { DEPLOYMENT_ERRORS } from "@/constants/errors.js";import { DeploymentStatus } from "@/models/Deployment.js";
class LogsController implements ILogsController { private logsService: ILogsService; private deploymentService: IDeploymentService; constructor(logsService: ILogsService, deplyService: IDeploymentService) { this.logsService = logsService; this.deploymentService = deplyService; }
async getLogsByProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const projectId = req.params.projectId; const user = req.user?.id as string; const result = await this.logsService.getProjectsLogs(projectId, user, {});
const response = LogMapper.toLogsResponse(result.logs, result.total); res.json(response); return; } catch (error) { next(error); } } async getLogsByDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { try { const deploymentId = req.params.deploymentId; const user = req.user?.id as string; const result = await this.logsService.getDeploymentLog(deploymentId, user, {});
const response = LogMapper.toLogsResponse(result.logs, result.total); res.json(response); return; } catch (error) { next(error); } }
async streamLogs(req: Request, res: Response, next: NextFunction): Promise<void> { const id = req.params.deploymentId; const user = req.user?.id as string; try { const deplomentExist = await this.deploymentService.getDeploymentById(id, user); if (!deplomentExist) { res.status(STATUS_CODES.NOT_FOUND).json({ status: 404, error: "not_found", message: DEPLOYMENT_ERRORS.NOT_FOUND, }); return; } if (!(deplomentExist.status === DeploymentStatus.BUILDING || deplomentExist.status === DeploymentStatus.QUEUED)) { res.status(STATUS_CODES.CONFLICT).json({ status: STATUS_CODES.CONFLICT, error: "Cant connect to deployment", message: DEPLOYMENT_ERRORS.NO_ACTIVE_DEPLOYMENT, }); return; } sseManager.addClient(v4(), id, res, req); } catch (error) { next(error); } }
async getData(req: Request, res: Response, next: NextFunction): Promise<void> { res.json({ clientCount: sseManager.getClientCount(), listerCount: sseManager.getListeners(), listerners: sseManager.getEventFns(), }); }}
export default LogsController;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import Stripe from "stripe";import { Request, Response, NextFunction } from "express";
import { IPaymentController } from "@/interfaces/controller/IPaymentController.js";import { IPaymentService } from "@/interfaces/service/IPaymentService.js";import { ENVS } from "@/config/env.config.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { issueAuthAccessCookies, issueAuthRefreshCookies } from "@/utils/authUtils.js";import AppError from "@/utils/AppError.js";import { stripe } from "@/config/stripe.config.js";import { PAYMENT_ERRORS } from "@/constants/errors.js";import { FRONTEND_PAYMENT_CANCEL_PATH, FRONTEND_PAYMENT_SUCCESS_PATH } from "@/constants/paths.js";import { PLANS } from "@/constants/plan.js";
class PaymentController implements IPaymentController { private paymentService: IPaymentService; constructor(service: IPaymentService) { this.paymentService = service; } async checkout(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const successUrl = ENVS.FRONTEND_URL + FRONTEND_PAYMENT_SUCCESS_PATH; const cancelUrl = ENVS.FRONTEND_URL + FRONTEND_PAYMENT_CANCEL_PATH; const { session, status } = await this.paymentService.createCheckoutSession(userId, successUrl, cancelUrl); if (!session || !status) { res.status(STATUS_CODES.BAD_REQUEST).json({ url: null, message: "No session , already pro member " + PAYMENT_ERRORS.NO_ACTION_TAKEN, }); return; } res.status(STATUS_CODES.OK).json({ url: session.url, sessionId: session.id }); } catch (error) { next(error); } } async cancelSubscription(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; await this.paymentService.handleCancelSubscription(userId); issueAuthAccessCookies(res, { id: userId, plan: PLANS.FREE.name }); issueAuthRefreshCookies(res, { id: userId, plan: PLANS.FREE.name }, { originalIssuedAt: Date.now(), currentRefresh: 1 }); res.status(STATUS_CODES.OK).json({ message: PAYMENT_ERRORS.SUBSCRIPTION_CANCELLED, status: true, }); } catch (error) { next(error); } } async webhook(req: Request, res: Response, next: NextFunction): Promise<void> { try { const sig = req.headers["stripe-signature"]; let event; const endpointSecret = ENVS.STRIPE_WEBHOOK_SECRET as string;
event = stripe.webhooks.constructEvent(req.body, sig ?? "", endpointSecret);
await this.paymentService.handleWebhookEvent(event); res.status(STATUS_CODES.OK).json({ received: true }); } catch (error) { next(error); } } async validate(req: Request, res: Response, next: NextFunction): Promise<void> { try { const sessionId = req.query.session_id; const userId = req.user?.id as string; const result = await this.paymentService.retriveSession(userId, sessionId as string); const { user } = result; issueAuthAccessCookies(res, { id: userId, plan: user?.plan as string }); issueAuthRefreshCookies(res, { id: userId, plan: user?.plan as string }, { originalIssuedAt: Date.now(), currentRefresh: 1 }); res.status(200).json({ valid: result.valid, customerName: result.customerName, currency: result.currency, amountPaid: result.amountPaid, paymentStatus: result.paymentStatus, }); } catch (err) { const error = err as Stripe.errors.StripeError; if (error.type === "StripeInvalidRequestError") { return next(new AppError(error.message, error.statusCode || STATUS_CODES.NOT_FOUND)); }
if (error.type === "StripeAuthenticationError") { return next(new AppError(error.message, error.statusCode || STATUS_CODES.INTERNAL_SERVER_ERROR)); }
if (error.type === "StripeAPIError") { return next(new AppError(error.message, error.statusCode || STATUS_CODES.SERVICE_UNAVAILABLE)); } next(err); } }}
export default PaymentController;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import { Request, Response, NextFunction } from "express";
import { IProjectController } from "@/interfaces/controller/IProjectController.js";import ProjectService from "@/services/project.service.js";import { checkSubdomainDTO, CreateProjectDTO, ProjectDeploymentUpdateDTO, QueryProjectDTO, UpdateProjectDTO, UpdateSubdomainDTO,} from "@/dtos/project.dto.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { ProjectMapper } from "@/mappers/ProjectMapper.js";import AppError from "@/utils/AppError.js";import { PROJECT_ERRORS } from "@/constants/errors.js";
class ProjectController implements IProjectController { private projectService: ProjectService;
constructor(projectService: ProjectService) { this.projectService = projectService; } async createProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const dto = req.validatedBody as CreateProjectDTO; const user = req.user?.id;
const dbResult = await this.projectService.createProject(dto, user || ""); if (!dbResult) { throw new AppError(PROJECT_ERRORS.CREATE_FAILED, STATUS_CODES.INTERNAL_SERVER_ERROR); } const response = ProjectMapper.toProjectResponse(dbResult, "full");
res.status(STATUS_CODES.CREATED).json(response); } catch (error) { next(error); } } async getAllProjects(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const query = req.validatedQuery as unknown as QueryProjectDTO; const result = await this.projectService.getAllProjects(userId, query); const response = ProjectMapper.toProjectsResponse( result.projects, result.total, query.page, query.limit, query.full ? "full" : "overview", );
res.status(STATUS_CODES.OK).json(response); } catch (err) { next(err); } } async getProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId; const include = req.query.include as string;
const result = await this.projectService.getProjectById(projectId, userId, include); if (!result) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(result, "overview"); res.status(STATUS_CODES.OK).json(response); } catch (err) { next(err); } } async getProjectComplete(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId; const include = req.query.include as string;
const result = await this.projectService.getProjectById(projectId, userId, include, true); if (!result) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(result, "full"); res.status(STATUS_CODES.OK).json(response); } catch (err) { next(err); } }
async getProjectSettings(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId; const include = req.query.include as string;
const result = await this.projectService.getProjectSettings(projectId, userId, include); if (!result) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(result, "setting"); res.status(STATUS_CODES.OK).json(response); } catch (err) { next(err); } } async updateProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId; const dto = req.validatedBody as UpdateProjectDTO;
const result = await this.projectService.updateProject(projectId, userId, dto); if (!result) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(result, "update"); res.status(STATUS_CODES.OK).json(response); } catch (err) { next(err); } } async updateSubdomain(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const dto = req.validatedBody as UpdateSubdomainDTO; const updatedProject = await this.projectService.changeProjectSubdomain(userId, dto.projectId, dto.newSubdomain.toLowerCase()); if (!updatedProject) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(updatedProject, "update"); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } } async checkSubdomainAvailable(req: Request, res: Response, next: NextFunction): Promise<void> { try { const dto = req.validatedQuery as checkSubdomainDTO; const result = await this.projectService.checkSubdomainAvaiable(dto.value.toLowerCase()); res.json({ available: result }); } catch (error) { next(error); } } async changeCurrentDeployment(req: Request, res: Response, next: NextFunction): Promise<void> { try { const dto = req.validatedBody as ProjectDeploymentUpdateDTO; const userId = req.user?.id as string; const projectId = req.params.projectId; const updatedProject = await this.projectService.changeProjectDeployment(userId, projectId, dto.newCurrentDeployment); if (!updatedProject) { res.status(STATUS_CODES.NOT_FOUND).json({ project: null }); return; } const response = ProjectMapper.toProjectResponse(updatedProject, "update"); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } }
async getProjectSimpleStats(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId;
const stats = await this.projectService.findProjectSimpleStats(userId, projectId); res.status(STATUS_CODES.OK).json({ stats }); } catch (error) { next(error); } } async deleteProject(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const projectId = req.params.projectId;
const result = await this.projectService.deleteProject(projectId, userId);
res.status(STATUS_CODES.NO_CONTENT).json({ deleted: result }); } catch (err) { next(err); } } async totalUsage(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const noOfmonthsData = 1; const results = await this.projectService.findTotalUsage(userId, noOfmonthsData); const data = ProjectMapper.toUsageMapper(results.projectRslts, results.deploys, noOfmonthsData); res.status(STATUS_CODES.OK).json(data); } catch (error) { next(error); } } async __getProjects(req: Request, res: Response, next: NextFunction): Promise<void> { try { const projectId = req.params.id; const project = await this.projectService.__getProjectById(projectId); if (project) { const response = ProjectMapper.toProjectResponse(project, "full"); res.json(response); return; } res.json({ project: null }); } catch (error) { next(error); } }}
export default ProjectController;12345678910111213141516171819import { COMMON_ERRORS } from "@/constants/errors.js";import { redisCacheService } from "@/instances.js";import AppError from "@/utils/AppError.js";import { STATUS_CODES } from "@/utils/statusCodes.js";import { NextFunction, Request, Response } from "express";export const getServerNotifications = async (req: Request, res: Response, next: NextFunction) => { try { const data = await redisCacheService.get<string>("server-notifications") if (!data) { res.status(404).json({ messgae: "Not found" }) return } res.status(200).json({ fromServer: data })
} catch (error: any) { console.log(error.message, error) next(new AppError(COMMON_ERRORS.SOMETHING_WENT_WRONG, STATUS_CODES.INTERNAL_SERVER_ERROR, error)); }};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import { ENVS } from "@/config/env.config.js";import { WEBHOOK_ERRORS } from "@/constants/errors.js";import { githubAppSlug } from "@/constants/gh.js";import { GithubCommitType } from "@/constants/types/github.js";import { IWebhookController } from "@/interfaces/controller/IWebhookController.js";import { IGithubService } from "@/interfaces/service/IGithubService.js";import { IWebhookService } from "@/interfaces/service/IWebhookService.js";import { GithubResponseMapper } from "@/mappers/GithubMapper.js";import AppError, { WebhookError } from "@/utils/AppError.js";
import { STATUS_CODES } from "@/utils/statusCodes.js";import { Request, Response, NextFunction } from "express";
class WebhookController implements IWebhookController { private webhookService: IWebhookService; private githubService: IGithubService;
constructor(webhookService: IWebhookService, githubService: IGithubService) { this.webhookService = webhookService; this.githubService = githubService; }
async getGithubConnectionUrl(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const installCompleteRedirectPath = req.get("x-redirect-path"); if (!installCompleteRedirectPath) { throw new WebhookError(WEBHOOK_ERRORS.INCOMPLE_DATA, STATUS_CODES.BAD_REQUEST); }
const token = await this.webhookService.webhookHandleNewRequest(userId, installCompleteRedirectPath); const installUrl = `https://github.com/apps/${githubAppSlug}/installations/new?state=${token}`;
res.status(STATUS_CODES.OK).json({ message: "Ok", url: installUrl }); } catch (error) { next(error); } }
async githubWebhook(req: Request, res: Response, next: NextFunction): Promise<void> { try { let deployResult = { status: "", reason: "" }; const { body } = req; const eventType = String(req.headers["x-github-event"]); switch (eventType) { case "push": const repository = body.repository; const sender = body.sender; const installationId = body.installation.id; const ref = body.ref; const allChanges: string[] = []; const headCommit = body.head_commit; let deployRequired = false; for (const commit of body.commits as GithubCommitType[]) { if (allChanges.length > 100) { deployRequired = true; break; } allChanges.push(...commit.added, ...commit.removed, ...commit.modified); } const meta = { sender, installationId, ref, allChanges, headCommit, deployRequired };
deployResult = await this.webhookService.webhookCodePushEvent(repository, meta); console.log({ deployResult }); break; case "installation": const action = body.action; switch (action) { case "created": await this.webhookService.webhookInstaltnCreateEvent(body.installation.id, body.installation.account, body.repositories); break;
case "deleted": await this.webhookService.webhookInstaltnDeleteEvent(body.installation.id, body.installation.account, body.repositories); break; } break; case "installation_repositories": const repoActions = body.action; switch (repoActions) { case "added": await this.webhookService.webhookRepositoryAddRemove(body.repositories_added, body.repositories_removed); break; case "removed": await this.webhookService.webhookRepositoryAddRemove(body.repositories_added, body.repositories_removed); break; } }
// console.log("\n---------------------\n", JSON.stringify(body, null, 2), "\n---------------------\n", // req.headers, "\n---------------------\n")
res.json({ status: 200, message: "success", deployResult }); } catch (error) { next(error); } }
async githubAppSetup(req: Request, res: Response, next: NextFunction): Promise<void> { const installationId = req.query.installation_id; const body = req.body;
let returnMessage = ""; let success = true;
try { returnMessage = await this.webhookService.githubSecondaryEvents(String(installationId), body.user); } catch (error: any) { success = false; returnMessage = error?.message || "Unknown error"; console.error(error);
try { if (error instanceof WebhookError) { await this.webhookService.removeGhbInstallation(String(installationId), body.user, true); } } catch (e: any) { console.error(e); } }
const urlFromState = body.redirectPath; const baseUrl = ENVS.FRONTEND_URL + (urlFromState || "/user/");
const params = new URLSearchParams({ tab: "provider", success: String(success), message: returnMessage, });
res.status(success ? STATUS_CODES.OK : STATUS_CODES.BAD_REQUEST).redirect(`${baseUrl}?${params.toString()}`); }
async getUserRepos(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const repos = await this.githubService.getUserRepos(userId); const response = GithubResponseMapper.toGithubReposResponse(repos);
res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } } async getUserRepo(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const owner = req.params.owner; const repo = req.params.repo; const repoResult = await this.githubService.getUserRepo(userId, owner, repo); const response = GithubResponseMapper.toGithubRepoResponse(repoResult); res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } } async getUserRepoBranches(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const owner = req.params.owner; const repo = req.params.repo; const branches = await this.githubService.getUserRepoBranches(userId, owner, repo); const response = GithubResponseMapper.toGithubRepoBranchResponse(branches);
res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } } async getUserAccountData(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string; const account = await this.githubService.getUserAccountData(userId); const response = GithubResponseMapper.toGithubAccountResponse(account);
res.status(STATUS_CODES.OK).json(response); } catch (error) { next(error); } }
async removeGithubApp(req: Request, res: Response, next: NextFunction): Promise<void> { try { const userId = req.user?.id as string;
const result = await this.webhookService.removeGhbInstallationManual(userId); res.status(STATUS_CODES.NO_CONTENT).json({ result }); } catch (error) { next(error); } }}
export default WebhookController;123456789import z from "zod";
export const AnalyticsQuerySchema = z.object({ range: z.string().optional(), interval: z.string().optional(), limit: z.coerce.number().int().min(1).max(100).default(10),});
export type AnalyticsQueryDTO = z.infer<typeof AnalyticsQuerySchema>;123456789101112131415161718192021222324import z from "zod";
export const SignUpSchema = z.object({ name: z.string().min(3).max(30), email: z.email(), password: z.string().min(8).max(64).regex(/\d/, "Password must contain at least one number"),});
export const LoginSchema = z.object({ email: z.email(), password: z.string().min(8),});export const VerifyOtpSchema = z.object({ email: z.email(), otp: z.number().min(6),});export const ResendOtpSchema = z.object({ email: z.email(),});
export type SignUpUserDTO = z.infer<typeof SignUpSchema>;export type LoginUserDTO = z.infer<typeof LoginSchema>;export type VerifyOtpDTO = z.infer<typeof VerifyOtpSchema>;export type ResendOtpDTO = z.infer<typeof ResendOtpSchema>;123456789101112131415161718192021import z from "zod";
import { mongoIdSchema } from "@/dtos/zodHelpers.js";import { DeploymentStatus } from "@/models/Deployment.js";
export const CreateDeploymentSchema = z.object({ projectId: mongoIdSchema,});export const DeploymentQueryScheme = z .object({ status: z.enum(Object.values(DeploymentStatus)).optional(), page: z.coerce.number().int().positive().default(1), limit: z.coerce.number().int().min(1).max(100).default(10), search: z.string().max(100).default("").optional(), include: z.string().optional(), full: z.string().optional(), }) .strict();
export type CreateDeploymentDTO = z.infer<typeof CreateDeploymentSchema>;export type QueryDeploymentDTO = z.infer<typeof DeploymentQueryScheme>;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import z from "zod";
import { mongoIdSchema } from "@/dtos/zodHelpers.js";import { ProjectProvider, ProjectStatus } from "@/models/Projects.js";import { DEPLOYMENT_ID_LENGTH, DEPLOYMENT_SEPARATOR_LENGTH, MAX_SUBDOMAIN_LENGTH } from "@/constants/subdomain.js";
export const envSchema = z .object({ name: z .string() .min(1, "Name is required") .max(100, "Name too long") .regex(/^[A-Z_][A-Z0-9_]*$/, "Name must be uppercase with underscores"), value: z.string().max(5000, "Value too long"), }) .strict();
export const CreateProjectSchema = z.object({ ghRepoId: z.number().optional(), provider: z.enum(ProjectProvider), isPrivate: z.boolean(), name: z.string().min(3, "Name should not exceed 3 charecters").max(50, "Name max 50 characters"), repoURL: z .string() .regex( /^(?:https?:\/\/)?(?:www\.)?(github\.com|gitlab\.com|bitbucket\.org)\/[\w.-]+\/[\w.-]+\/?$/, "Invalid repository URL (GitHub, GitLab, Bitbucket supported)", ), branch: z.string().min(1, "Branch cannot be empty").default("main").optional(), buildCommand: z .string() .regex(/^[a-zA-Z0-9_\-./ ]+$/, "Build command contains invalid characters") .optional() .default("build"), // installCommand: z // .string() // .regex(/^[a-zA-Z0-9_\-./ ]+$/, "Install command contains invalid characters") // .optional() // .default("install"), rootDir: z .string() .trim() .min(1, "Root directory cannot be empty") .regex( /^\/(?!\.\.)[a-zA-Z0-9\/_-]*$/, "Path must start with / and contain only alphanumeric characters, hyphens, underscores, and forward slashes", ) .refine( (path) => !path.includes("..") && !["/etc", "/root", "/sys", "/proc", "/dev"].some((dir) => path.startsWith(dir)), "Invalid or restricted path", ) .default("/") .catch("/") .optional(), outputDirectory: z.string().optional().default("dist"), env: z.array(envSchema).max(100).default([]).optional(),});
export const UpdateProjectSchema = z.object({ name: z.string().min(3, "Name should be at least 3 charecters").max(50, "Name max 50 characters").optional(), branch: z.string().optional(), buildCommand: z .string() .regex(/^[a-zA-Z0-9_\-./ ]+$/, "Build command contains invalid characters") .optional(), installCommand: z .string() .regex(/^[a-zA-Z0-9_\-./ ]+$/, "Install command contains invalid characters") .optional(), rootDir: z .string() .trim() .min(1, "Root directory cannot be empty") .regex( /^\/(?!\.\.)[a-zA-Z0-9\/_-]*$/, "Path must start with / and contain only alphanumeric characters, hyphens, underscores, and forward slashes", ) .refine( (path) => !path.includes("..") && !["/etc", "/root", "/sys", "/proc", "/dev"].some((dir) => path.startsWith(dir)), "Invalid or restricted path", ) .catch("/") .optional(), rewriteNonFilePaths: z.boolean().optional(), autoDeployEnabled: z.boolean().optional(), outputDirectory: z.string().optional(), env: z.array(envSchema).max(100).optional(), isDisabled: z.boolean().optional(), projectId: z.string(),});
export const ProjectQuerySchema = z .object({ status: z.enum(Object.values(ProjectStatus)).optional(), page: z.coerce.number().int().positive().default(1), limit: z.coerce.number().int().min(1).max(100).default(10), search: z.string().max(100).optional().default(""), include: z.string().optional(), full: z.string().optional(), }) .strict();
export const ProjectSubdomainSchema = z.object({ projectId: mongoIdSchema, newSubdomain: z .string() .min(3) .max(MAX_SUBDOMAIN_LENGTH - (DEPLOYMENT_ID_LENGTH + DEPLOYMENT_SEPARATOR_LENGTH)) .regex(/^[a-z0-9-]+$/, "Only lowercase letters, numbers and hyphens allowed") .regex(/^[a-z0-9]/, "Must start with a letter or number") .regex(/[a-z0-9]$/, "Must end with a letter or number"),});export const SubdomainQuerySchema = z.object({ value: z .string() .min(3) .max(MAX_SUBDOMAIN_LENGTH - (DEPLOYMENT_ID_LENGTH + DEPLOYMENT_SEPARATOR_LENGTH)) .regex(/^[a-z0-9-]+$/, "Only lowercase letters, numbers and hyphens allowed") .regex(/^[a-z0-9]/, "Must start with a letter or number") .regex(/[a-z0-9]$/, "Must end with a letter or number"),});export const ProjectDeploymentUpdateSchema = z.object({ newCurrentDeployment: mongoIdSchema,});
export type CreateProjectDTO = z.infer<typeof CreateProjectSchema>;export type UpdateProjectDTO = z.infer<typeof UpdateProjectSchema>;export type QueryProjectDTO = z.infer<typeof ProjectQuerySchema>;export type UpdateSubdomainDTO = z.infer<typeof ProjectSubdomainSchema>;export type checkSubdomainDTO = z.infer<typeof SubdomainQuerySchema>;export type ProjectDeploymentUpdateDTO = z.infer<typeof ProjectDeploymentUpdateSchema>;1234import { z } from "zod";import mongoose from "mongoose";
export const mongoIdSchema = z.string().refine((id) => mongoose.Types.ObjectId.isValid(id), { message: "Invalid MongoDB ObjectId" });12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import { IKafkaEventConsumer } from "@/interfaces/consumers/IKafkaEventConsumer.js";import { Consumer, Kafka } from "kafkajs";import universalKafkaHandler, { getAllTopics, EVENT_REGISTRY, getDeploymentLogsTopic } from "@/events/regitry.js";
class KafkaEventConsumer implements IKafkaEventConsumer { private kafka: Kafka; private logsConsumer: Consumer; private analyticsConsumer: Consumer; private isRunning = false;
constructor(kafka: Kafka) { this.kafka = kafka; this.logsConsumer = this.kafka.consumer({ groupId: "lynfera-logs-group", sessionTimeout: 45000, heartbeatInterval: 3000, }); this.analyticsConsumer = this.kafka.consumer({ groupId: "lynfera-analytics-group", sessionTimeout: 45000, heartbeatInterval: 3000, }); } async start() { if (this.isRunning) { console.log("Kafka already running"); return; } try { await Promise.all([this.logsConsumer.connect(), this.analyticsConsumer.connect()]); console.log(" Kafka consumers connected");
const [logsTopics, analyticsTopics] = getAllTopics(); await this.logsConsumer.subscribe({ topics: logsTopics }); await this.analyticsConsumer.subscribe({ topics: analyticsTopics }); console.log(` Subscribed to topics:`, [...logsTopics, ...analyticsTopics]);
await this.logsConsumer.run({ autoCommit: false, eachBatch: universalKafkaHandler, }); await this.analyticsConsumer.run({ autoCommit: true, eachBatch: universalKafkaHandler, });
this.isRunning = true; console.log("-------------------------------Kafka consumers started successfully-------------------------------"); } catch (error) { console.error("Failed to start Kafka consumers:", error); throw error; } } getDeploymentLogsTopic() { return getDeploymentLogsTopic(); } pauseLogs() { console.log(this.getDeploymentLogsTopic(), "Pasuing logs topics...."); this.logsConsumer.pause([{ topic: this.getDeploymentLogsTopic() }]); } resumeLogs() { console.log(this.getDeploymentLogsTopic(), "Resume logs topics...."); this.logsConsumer.resume([{ topic: this.getDeploymentLogsTopic() }]); }
async stop(): Promise<void> { if (!this.isRunning) { return; }
try { await Promise.all([this.logsConsumer.disconnect(), this.analyticsConsumer.disconnect()]); this.isRunning = false; console.log("Kafka consumer stopped"); } catch (error) { console.error("Error stopping Kafka consumer:", error); throw error; } }}
export default KafkaEventConsumer;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import { EventEmitter } from "events";import { Response, Request } from "express";
class DeploymentEmitter extends EventEmitter { onEvent(eventString: string, callback: (log: any) => void) { this.on(eventString, callback); } offEvent(eventString: string, callback: (log: any) => void) { this.off(eventString, callback); } emitEvents(eventString: string, log: any, type: string) { const emitData = { type, data: log }; this.emit(eventString, emitData); }
offAllEvents(eventString: string) { this.removeAllListeners(eventString); }}export const deploymentEmitter = new DeploymentEmitter();
interface SSEClient { deploymentId: string; res: Response; listener: (data: any) => void; errors: number;}
class SSEManager { private emitter: DeploymentEmitter; private clients: Map<string, SSEClient>; private interval: NodeJS.Timeout;
constructor() { this.emitter = deploymentEmitter; this.emitter.setMaxListeners(1000); this.clients = new Map<string, SSEClient>(); this.interval = setInterval(() => { const clients = this.clients.entries(); for (const [client, data] of clients) { try { data.res.write(`:heartbeat\n\n`); } catch (error) { console.log("Error on heartbeat SSEClient"); this.removeClient(client); } } }, 30 * 1000); }
addClient(clientId: string, deploymentId: string, res: Response, req: Request) { res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); res.setHeader("X-Accel-Buffering", "no");
res.write(`data: ${JSON.stringify({ type: "connected" })}\n\n`);
req.on("close", () => { this.removeClient(clientId); });
const listener = (event: any) => { try { res.write(`data: ${JSON.stringify(event)}\n\n`); } catch (error) { const old = this.clients.get(clientId) as SSEClient; console.log("Error on data sending SSEClient"); if (old.errors > 3) { this.removeClient(clientId); // this.emitter.offAllEvents(deploymentId); return; } this.clients.set(clientId, { ...old, errors: old.errors + 1 }); } };
this.emitter.onEvent(deploymentId, listener);
this.clients.set(clientId, { deploymentId, res, errors: 0, listener, });
console.log(`Client connected: ${clientId}, Active clients: ${this.clients.size}`); }
removeClient(clientId: string) { const client = this.clients.get(clientId); if (!client) return;
this.emitter.offEvent(client.deploymentId, client.listener);
try { if (!client.res.writableEnded) { client.res.write('event: close\ndata: {"status":"complete"}\n\n'); client.res.end(); } } catch (error) { console.log("Error on client remove SSEClient"); this.emitter.offAllEvents(client.deploymentId); }
this.clients.delete(clientId);
console.log(`Client removed: ${clientId}, Active clients: ${this.clients.size}, ${this.clients}`); }
closeClientsByDeployment(deplomentId: string) { this.emitter.offAllEvents(deplomentId); }
getClientCount(): number { return this.clients.size; }
getListeners(): (string | symbol)[] { const names = this.emitter.eventNames(); return names; } getEventFns(): any { const names = this.emitter.eventNames(); const arr = names.map((name) => ({ eventString: name, fns: this.emitter.listeners(name).map((fn) => fn.toString()), })); return arr; }
cleanup() { console.log("Clean up SSE Map"); for (const [clientId] of this.clients) { this.removeClient(clientId); } clearInterval(this.interval); }}
export const sseManager = new SSEManager();.dockerignoreAdded+13
.gitignoreAdded+2
.prettierrcAdded+11
DockerfileAdded+34
README.md+5-3
ecosystem.config.cjsAdded+22
migrations/create-indexes.tsAdded+118
package-lock.jsonAdded
package.jsonAdded+64
src/app.tsAdded+40
src/cache/redisCache.tsAdded+64
src/config/clickhouse.config.tsAdded+14
src/config/cloud.config.tsAdded+26
src/config/cookie.config.tsAdded+18
src/config/cors.config.tsAdded+13
src/config/email.config.tsAdded+5
src/config/env.config.tsAdded+72
src/config/kafka.config.tsAdded+20
src/config/mongo.config.tsAdded+18
src/config/oauthStrategies/githubLogin.tsAdded+19
src/config/oauthStrategies/googleLogin.tsAdded+19
src/config/oauthStrategies/jwt.tsAdded+27
src/config/passport.tsAdded+8
src/config/rate-limiter.config.tsAdded+31
src/config/redis.config.tsAdded+3
src/config/stripe.config.tsAdded+3
src/constants/analytics.tsAdded+6
src/constants/errors.tsAdded+90
src/constants/gh.tsAdded+11
src/constants/paths.tsAdded+13
src/constants/plan.tsAdded+36
src/constants/populates/deployment.populate.tsAdded+12
src/constants/populates/project.populate.tsAdded+46
src/constants/subdomain.tsAdded+628
src/constants/types/github.tsAdded+83
src/controllers/analyticsController.tsAdded+109
src/controllers/authController.tsAdded+280
src/controllers/deploymentController.tsAdded+149
src/controllers/logsController.tsAdded+84
src/controllers/paymentController.tsAdded+99
src/controllers/projectController.tsAdded+218
src/controllers/serverDataOnlyController.tsAdded+19
src/controllers/webhookController.tsAdded+194
src/dtos/analytics.dto.tsAdded+9
src/dtos/auth.dto.tsAdded+24
src/dtos/deployment.dto.tsAdded+21
src/dtos/project.dto.tsAdded+131
src/dtos/zodHelpers.tsAdded+4
src/events/consumers.tsAdded+82
src/events/deploymentEmitter.tsAdded+141