| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1 | import { PrismaClient } from "@prisma/client"; |
| 2 | import express from "express"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 3 | import fs from "node:fs"; |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 4 | import { env } from "node:process"; |
| 5 | import axios from "axios"; |
| 6 | import { GithubClient } from "./github"; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 7 | import { AppManager } from "./app_manager"; |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 8 | import { z } from "zod"; |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 9 | import { ProjectMonitor, WorkerSchema } from "./project_monitor"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 10 | import tmp from "tmp"; |
| 11 | import { NodeJSAnalyzer } from "./lib/nodejs"; |
| 12 | import shell from "shelljs"; |
| 13 | import { RealFileSystem } from "./lib/fs"; |
| 14 | import path from "node:path"; |
| 15 | |
| 16 | async function generateKey(root: string): Promise<[string, string]> { |
| 17 | const privKeyPath = path.join(root, "key"); |
| 18 | const pubKeyPath = path.join(root, "key.pub"); |
| 19 | if (shell.exec(`ssh-keygen -t ed25519 -f ${privKeyPath} -N ""`).code !== 0) { |
| 20 | throw new Error("Failed to generate SSH key pair"); |
| 21 | } |
| 22 | const publicKey = await fs.promises.readFile(pubKeyPath, "utf8"); |
| 23 | const privateKey = await fs.promises.readFile(privKeyPath, "utf8"); |
| 24 | return [publicKey, privateKey]; |
| 25 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 26 | |
| 27 | const db = new PrismaClient(); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 28 | const appManager = new AppManager(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 29 | |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 30 | const projectMonitors = new Map<number, ProjectMonitor>(); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 31 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 32 | const handleProjectCreate: express.Handler = async (req, resp) => { |
| 33 | try { |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 34 | const tmpDir = tmp.dirSync().name; |
| 35 | const [publicKey, privateKey] = await generateKey(tmpDir); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 36 | const { id } = await db.project.create({ |
| 37 | data: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 38 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 39 | name: req.body.name, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 40 | deployKey: privateKey, |
| 41 | deployKeyPublic: publicKey, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 42 | }, |
| 43 | }); |
| 44 | resp.status(200); |
| 45 | resp.header("Content-Type", "application/json"); |
| 46 | resp.write( |
| 47 | JSON.stringify({ |
| gio | 74ab785 | 2025-05-13 13:19:31 +0000 | [diff] [blame] | 48 | id: id.toString(), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 49 | }), |
| 50 | ); |
| 51 | } catch (e) { |
| 52 | console.log(e); |
| 53 | resp.status(500); |
| 54 | } finally { |
| 55 | resp.end(); |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | const handleProjectAll: express.Handler = async (req, resp) => { |
| 60 | try { |
| 61 | const r = await db.project.findMany({ |
| 62 | where: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 63 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 64 | }, |
| 65 | }); |
| 66 | resp.status(200); |
| 67 | resp.header("Content-Type", "application/json"); |
| 68 | resp.write( |
| 69 | JSON.stringify( |
| 70 | r.map((p) => ({ |
| 71 | id: p.id.toString(), |
| 72 | name: p.name, |
| 73 | })), |
| 74 | ), |
| 75 | ); |
| 76 | } catch (e) { |
| 77 | console.log(e); |
| 78 | resp.status(500); |
| 79 | } finally { |
| 80 | resp.end(); |
| 81 | } |
| 82 | }; |
| 83 | |
| 84 | const handleSave: express.Handler = async (req, resp) => { |
| 85 | try { |
| 86 | await db.project.update({ |
| 87 | where: { |
| 88 | id: Number(req.params["projectId"]), |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 89 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 90 | }, |
| 91 | data: { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 92 | draft: JSON.stringify(req.body), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 93 | }, |
| 94 | }); |
| 95 | resp.status(200); |
| 96 | } catch (e) { |
| 97 | console.log(e); |
| 98 | resp.status(500); |
| 99 | } finally { |
| 100 | resp.end(); |
| 101 | } |
| 102 | }; |
| 103 | |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 104 | function handleSavedGet(state: "deploy" | "draft"): express.Handler { |
| 105 | return async (req, resp) => { |
| 106 | try { |
| 107 | const r = await db.project.findUnique({ |
| 108 | where: { |
| 109 | id: Number(req.params["projectId"]), |
| 110 | userId: resp.locals.userId, |
| 111 | }, |
| 112 | select: { |
| 113 | state: true, |
| 114 | draft: true, |
| 115 | }, |
| 116 | }); |
| 117 | if (r == null) { |
| 118 | resp.status(404); |
| 119 | return; |
| 120 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 121 | resp.status(200); |
| 122 | resp.header("content-type", "application/json"); |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 123 | if (state === "deploy") { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 124 | if (r.state == null) { |
| 125 | resp.send({ |
| 126 | nodes: [], |
| 127 | edges: [], |
| 128 | viewport: { x: 0, y: 0, zoom: 1 }, |
| 129 | }); |
| 130 | } else { |
| 131 | resp.send(JSON.parse(Buffer.from(r.state).toString("utf8"))); |
| 132 | } |
| 133 | } else { |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 134 | if (r.draft == null) { |
| 135 | if (r.state == null) { |
| 136 | resp.send({ |
| 137 | nodes: [], |
| 138 | edges: [], |
| 139 | viewport: { x: 0, y: 0, zoom: 1 }, |
| 140 | }); |
| 141 | } else { |
| 142 | resp.send(JSON.parse(Buffer.from(r.state).toString("utf8"))); |
| 143 | } |
| 144 | } else { |
| 145 | resp.send(JSON.parse(Buffer.from(r.draft).toString("utf8"))); |
| 146 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 147 | } |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 148 | } catch (e) { |
| 149 | console.log(e); |
| 150 | resp.status(500); |
| 151 | } finally { |
| 152 | resp.end(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 153 | } |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 154 | }; |
| 155 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 156 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 157 | const projectDeleteReqSchema = z.object({ |
| 158 | state: z.optional(z.nullable(z.string())), |
| 159 | }); |
| 160 | |
| 161 | const handleProjectDelete: express.Handler = async (req, resp) => { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 162 | try { |
| 163 | const projectId = Number(req.params["projectId"]); |
| 164 | const p = await db.project.findUnique({ |
| 165 | where: { |
| 166 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 167 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 168 | }, |
| 169 | select: { |
| 170 | instanceId: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 171 | githubToken: true, |
| 172 | deployKeyPublic: true, |
| 173 | state: true, |
| 174 | draft: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 175 | }, |
| 176 | }); |
| 177 | if (p === null) { |
| 178 | resp.status(404); |
| 179 | return; |
| 180 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 181 | const parseResult = projectDeleteReqSchema.safeParse(req.body); |
| 182 | if (!parseResult.success) { |
| 183 | resp.status(400); |
| 184 | resp.write(JSON.stringify({ error: "Invalid request body", issues: parseResult.error.format() })); |
| 185 | return; |
| gio | e440db8 | 2025-05-13 12:21:44 +0000 | [diff] [blame] | 186 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 187 | if (p.githubToken && p.deployKeyPublic) { |
| 188 | const allRepos = [ |
| 189 | ...new Set([ |
| 190 | ...extractGithubRepos(p.state), |
| 191 | ...extractGithubRepos(p.draft), |
| 192 | ...extractGithubRepos(parseResult.data.state), |
| 193 | ]), |
| 194 | ]; |
| 195 | if (allRepos.length > 0) { |
| 196 | const diff: RepoDiff = { toDelete: allRepos, toAdd: [] }; |
| 197 | const github = new GithubClient(p.githubToken); |
| 198 | await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR); |
| 199 | console.log( |
| 200 | `Attempted to remove deploy keys for project ${projectId} from associated GitHub repositories.`, |
| 201 | ); |
| 202 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 203 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 204 | if (p.instanceId !== null) { |
| 205 | if (!(await appManager.removeInstance(p.instanceId))) { |
| 206 | resp.status(500); |
| 207 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 208 | return; |
| 209 | } |
| 210 | } |
| 211 | await db.project.delete({ |
| 212 | where: { |
| 213 | id: projectId, |
| 214 | }, |
| 215 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 216 | resp.status(200); |
| 217 | } catch (e) { |
| 218 | console.log(e); |
| 219 | resp.status(500); |
| 220 | } finally { |
| 221 | resp.end(); |
| 222 | } |
| 223 | }; |
| 224 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 225 | function extractGithubRepos(serializedState: string | null | undefined): string[] { |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 226 | if (!serializedState) { |
| 227 | return []; |
| 228 | } |
| 229 | try { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 230 | const stateObj = JSON.parse(serializedState); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 231 | const githubNodes = stateObj.nodes.filter( |
| 232 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 233 | (n: any) => n.type === "github" && n.data?.repository?.id, |
| 234 | ); |
| 235 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 236 | return githubNodes.map((n: any) => n.data.repository.sshURL); |
| 237 | } catch (error) { |
| 238 | console.error("Failed to parse state or extract GitHub repos:", error); |
| 239 | return []; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | type RepoDiff = { |
| 244 | toAdd?: string[]; |
| 245 | toDelete?: string[]; |
| 246 | }; |
| 247 | |
| 248 | function calculateRepoDiff(oldRepos: string[], newRepos: string[]): RepoDiff { |
| 249 | const toAdd = newRepos.filter((repo) => !oldRepos.includes(repo)); |
| 250 | const toDelete = oldRepos.filter((repo) => !newRepos.includes(repo)); |
| 251 | return { toAdd, toDelete }; |
| 252 | } |
| 253 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 254 | async function manageGithubRepos( |
| 255 | github: GithubClient, |
| 256 | diff: RepoDiff, |
| 257 | deployKey: string, |
| 258 | publicAddr?: string, |
| 259 | ): Promise<void> { |
| 260 | console.log(publicAddr); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 261 | for (const repoUrl of diff.toDelete ?? []) { |
| 262 | try { |
| 263 | await github.removeDeployKey(repoUrl, deployKey); |
| 264 | console.log(`Removed deploy key from repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 265 | if (publicAddr) { |
| 266 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 267 | await github.removePushWebhook(repoUrl, webhookCallbackUrl); |
| 268 | console.log(`Removed push webhook from repository ${repoUrl}`); |
| 269 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 270 | } catch (error) { |
| 271 | console.error(`Failed to remove deploy key from repository ${repoUrl}:`, error); |
| 272 | } |
| 273 | } |
| 274 | for (const repoUrl of diff.toAdd ?? []) { |
| 275 | try { |
| 276 | await github.addDeployKey(repoUrl, deployKey); |
| 277 | console.log(`Added deploy key to repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 278 | if (publicAddr) { |
| 279 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 280 | await github.addPushWebhook(repoUrl, webhookCallbackUrl); |
| 281 | console.log(`Added push webhook to repository ${repoUrl}`); |
| 282 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 283 | } catch (error) { |
| 284 | console.error(`Failed to add deploy key from repository ${repoUrl}:`, error); |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 289 | const handleDeploy: express.Handler = async (req, resp) => { |
| 290 | try { |
| 291 | const projectId = Number(req.params["projectId"]); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 292 | const state = JSON.stringify(req.body.state); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 293 | const p = await db.project.findUnique({ |
| 294 | where: { |
| 295 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 296 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 297 | }, |
| 298 | select: { |
| 299 | instanceId: true, |
| 300 | githubToken: true, |
| 301 | deployKey: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 302 | deployKeyPublic: true, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 303 | state: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 304 | }, |
| 305 | }); |
| 306 | if (p === null) { |
| 307 | resp.status(404); |
| 308 | return; |
| 309 | } |
| 310 | await db.project.update({ |
| 311 | where: { |
| 312 | id: projectId, |
| 313 | }, |
| 314 | data: { |
| 315 | draft: state, |
| 316 | }, |
| 317 | }); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 318 | let deployKey: string | null = p.deployKey; |
| 319 | let deployKeyPublic: string | null = p.deployKeyPublic; |
| 320 | if (deployKeyPublic == null) { |
| 321 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 322 | await db.project.update({ |
| 323 | where: { id: projectId }, |
| 324 | data: { deployKeyPublic, deployKey }, |
| 325 | }); |
| 326 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 327 | let diff: RepoDiff | null = null; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 328 | const config = req.body.config; |
| 329 | config.input.key = { |
| 330 | public: deployKeyPublic, |
| 331 | private: deployKey, |
| 332 | }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 333 | try { |
| 334 | if (p.instanceId == null) { |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 335 | const deployResponse = await appManager.deploy(config); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 336 | await db.project.update({ |
| 337 | where: { |
| 338 | id: projectId, |
| 339 | }, |
| 340 | data: { |
| 341 | state, |
| 342 | draft: null, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 343 | instanceId: deployResponse.id, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 344 | access: JSON.stringify(deployResponse.access), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 345 | }, |
| 346 | }); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 347 | diff = { toAdd: extractGithubRepos(state) }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 348 | } else { |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 349 | const deployResponse = await appManager.update(p.instanceId, config); |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 350 | diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(state)); |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 351 | await db.project.update({ |
| 352 | where: { |
| 353 | id: projectId, |
| 354 | }, |
| 355 | data: { |
| 356 | state, |
| 357 | draft: null, |
| 358 | access: JSON.stringify(deployResponse.access), |
| 359 | }, |
| 360 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 361 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 362 | if (diff && p.githubToken && deployKey) { |
| 363 | const github = new GithubClient(p.githubToken); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 364 | await manageGithubRepos(github, diff, deployKeyPublic!, env.PUBLIC_ADDR); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 365 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 366 | resp.status(200); |
| 367 | } catch (error) { |
| 368 | console.error("Deployment error:", error); |
| 369 | resp.status(500); |
| 370 | resp.write(JSON.stringify({ error: "Deployment failed" })); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 371 | } |
| 372 | } catch (e) { |
| 373 | console.log(e); |
| 374 | resp.status(500); |
| 375 | } finally { |
| 376 | resp.end(); |
| 377 | } |
| 378 | }; |
| 379 | |
| 380 | const handleStatus: express.Handler = async (req, resp) => { |
| 381 | try { |
| 382 | const projectId = Number(req.params["projectId"]); |
| 383 | const p = await db.project.findUnique({ |
| 384 | where: { |
| 385 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 386 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 387 | }, |
| 388 | select: { |
| 389 | instanceId: true, |
| 390 | }, |
| 391 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 392 | if (p === null) { |
| 393 | resp.status(404); |
| 394 | return; |
| 395 | } |
| 396 | if (p.instanceId == null) { |
| 397 | resp.status(404); |
| 398 | return; |
| 399 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 400 | try { |
| 401 | const status = await appManager.getStatus(p.instanceId); |
| 402 | resp.status(200); |
| 403 | resp.write(JSON.stringify(status)); |
| 404 | } catch (error) { |
| 405 | console.error("Error getting status:", error); |
| 406 | resp.status(500); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 407 | } |
| 408 | } catch (e) { |
| 409 | console.log(e); |
| 410 | resp.status(500); |
| 411 | } finally { |
| 412 | resp.end(); |
| 413 | } |
| 414 | }; |
| 415 | |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 416 | const handleRemoveDeployment: express.Handler = async (req, resp) => { |
| 417 | try { |
| 418 | const projectId = Number(req.params["projectId"]); |
| 419 | const p = await db.project.findUnique({ |
| 420 | where: { |
| 421 | id: projectId, |
| 422 | userId: resp.locals.userId, |
| 423 | }, |
| 424 | select: { |
| 425 | instanceId: true, |
| 426 | githubToken: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 427 | deployKeyPublic: true, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 428 | state: true, |
| 429 | draft: true, |
| 430 | }, |
| 431 | }); |
| 432 | if (p === null) { |
| 433 | resp.status(404); |
| 434 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 435 | return; |
| 436 | } |
| 437 | if (p.instanceId == null) { |
| 438 | resp.status(400); |
| 439 | resp.write(JSON.stringify({ error: "Project not deployed" })); |
| 440 | return; |
| 441 | } |
| 442 | const removed = await appManager.removeInstance(p.instanceId); |
| 443 | if (!removed) { |
| 444 | resp.status(500); |
| 445 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 446 | return; |
| 447 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 448 | if (p.githubToken && p.deployKeyPublic && p.state) { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 449 | try { |
| 450 | const github = new GithubClient(p.githubToken); |
| 451 | const repos = extractGithubRepos(p.state); |
| 452 | const diff = { toDelete: repos, toAdd: [] }; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 453 | await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 454 | } catch (error) { |
| 455 | console.error("Error removing GitHub deploy keys:", error); |
| 456 | } |
| 457 | } |
| 458 | await db.project.update({ |
| 459 | where: { |
| 460 | id: projectId, |
| 461 | }, |
| 462 | data: { |
| 463 | instanceId: null, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 464 | deployKeyPublic: null, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 465 | access: null, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 466 | state: null, |
| 467 | draft: p.draft ?? p.state, |
| 468 | }, |
| 469 | }); |
| 470 | resp.status(200); |
| 471 | resp.write(JSON.stringify({ success: true })); |
| 472 | } catch (e) { |
| 473 | console.error("Error removing deployment:", e); |
| 474 | resp.status(500); |
| 475 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 476 | } finally { |
| 477 | resp.end(); |
| 478 | } |
| 479 | }; |
| 480 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 481 | const handleGithubRepos: express.Handler = async (req, resp) => { |
| 482 | try { |
| 483 | const projectId = Number(req.params["projectId"]); |
| 484 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 485 | where: { |
| 486 | id: projectId, |
| 487 | userId: resp.locals.userId, |
| 488 | }, |
| 489 | select: { |
| 490 | githubToken: true, |
| 491 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 492 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 493 | if (!project?.githubToken) { |
| 494 | resp.status(400); |
| 495 | resp.write(JSON.stringify({ error: "GitHub token not configured" })); |
| 496 | return; |
| 497 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 498 | const github = new GithubClient(project.githubToken); |
| 499 | const repositories = await github.getRepositories(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 500 | resp.status(200); |
| 501 | resp.header("Content-Type", "application/json"); |
| 502 | resp.write(JSON.stringify(repositories)); |
| 503 | } catch (e) { |
| 504 | console.log(e); |
| 505 | resp.status(500); |
| 506 | resp.write(JSON.stringify({ error: "Failed to fetch repositories" })); |
| 507 | } finally { |
| 508 | resp.end(); |
| 509 | } |
| 510 | }; |
| 511 | |
| 512 | const handleUpdateGithubToken: express.Handler = async (req, resp) => { |
| 513 | try { |
| 514 | const projectId = Number(req.params["projectId"]); |
| 515 | const { githubToken } = req.body; |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 516 | await db.project.update({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 517 | where: { |
| 518 | id: projectId, |
| 519 | userId: resp.locals.userId, |
| 520 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 521 | data: { githubToken }, |
| 522 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 523 | resp.status(200); |
| 524 | } catch (e) { |
| 525 | console.log(e); |
| 526 | resp.status(500); |
| 527 | } finally { |
| 528 | resp.end(); |
| 529 | } |
| 530 | }; |
| 531 | |
| 532 | const handleEnv: express.Handler = async (req, resp) => { |
| 533 | const projectId = Number(req.params["projectId"]); |
| 534 | try { |
| 535 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 536 | where: { |
| 537 | id: projectId, |
| 538 | userId: resp.locals.userId, |
| 539 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 540 | select: { |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 541 | deployKeyPublic: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 542 | githubToken: true, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 543 | access: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 544 | instanceId: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 545 | }, |
| 546 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 547 | if (!project) { |
| 548 | resp.status(404); |
| 549 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 550 | return; |
| 551 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 552 | const monitor = projectMonitors.get(projectId); |
| 553 | const serviceNames = monitor ? monitor.getAllServiceNames() : []; |
| 554 | const services = serviceNames.map((name) => ({ |
| 555 | name, |
| 556 | workers: [...(monitor ? monitor.getWorkerStatusesForService(name) : new Map()).entries()].map( |
| 557 | ([id, status]) => ({ |
| 558 | ...status, |
| 559 | id, |
| 560 | }), |
| 561 | ), |
| 562 | })); |
| 563 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 564 | resp.status(200); |
| 565 | resp.write( |
| 566 | JSON.stringify({ |
| gio | 376a81d | 2025-05-20 06:42:01 +0000 | [diff] [blame] | 567 | managerAddr: env.INTERNAL_API_ADDR, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 568 | deployKeyPublic: project.deployKeyPublic == null ? undefined : project.deployKeyPublic, |
| 569 | instanceId: project.instanceId == null ? undefined : project.instanceId, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 570 | access: JSON.parse(project.access ?? "[]"), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 571 | integrations: { |
| 572 | github: !!project.githubToken, |
| 573 | }, |
| 574 | networks: [ |
| 575 | { |
| gio | 3304672 | 2025-05-16 14:49:55 +0000 | [diff] [blame] | 576 | name: "Trial", |
| 577 | domain: "trial.dodoapp.xyz", |
| gio | 6d8b71c | 2025-05-19 12:57:35 +0000 | [diff] [blame] | 578 | hasAuth: false, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 579 | }, |
| gio | b1c5c45 | 2025-05-21 04:16:54 +0000 | [diff] [blame] | 580 | // TODO(gio): Remove |
| 581 | ].concat( |
| 582 | resp.locals.username !== "gio" |
| 583 | ? [] |
| 584 | : [ |
| 585 | { |
| 586 | name: "Public", |
| 587 | domain: "v1.dodo.cloud", |
| 588 | hasAuth: true, |
| 589 | }, |
| 590 | { |
| 591 | name: "Private", |
| 592 | domain: "p.v1.dodo.cloud", |
| 593 | hasAuth: true, |
| 594 | }, |
| 595 | ], |
| 596 | ), |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 597 | services, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 598 | user: { |
| 599 | id: resp.locals.userId, |
| 600 | username: resp.locals.username, |
| 601 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 602 | }), |
| 603 | ); |
| 604 | } catch (error) { |
| 605 | console.error("Error checking integrations:", error); |
| 606 | resp.status(500); |
| 607 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 608 | } finally { |
| 609 | resp.end(); |
| 610 | } |
| 611 | }; |
| 612 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 613 | const handleServiceLogs: express.Handler = async (req, resp) => { |
| 614 | try { |
| 615 | const projectId = Number(req.params["projectId"]); |
| 616 | const service = req.params["service"]; |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 617 | const workerId = req.params["workerId"]; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 618 | const project = await db.project.findUnique({ |
| 619 | where: { |
| 620 | id: projectId, |
| 621 | userId: resp.locals.userId, |
| 622 | }, |
| 623 | }); |
| 624 | if (project == null) { |
| 625 | resp.status(404); |
| 626 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 627 | return; |
| 628 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 629 | const monitor = projectMonitors.get(projectId); |
| 630 | if (!monitor || !monitor.hasLogs()) { |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 631 | resp.status(404); |
| 632 | resp.write(JSON.stringify({ error: "No logs found for this project" })); |
| 633 | return; |
| 634 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 635 | const serviceLog = monitor.getWorkerLog(service, workerId); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 636 | if (!serviceLog) { |
| 637 | resp.status(404); |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 638 | resp.write(JSON.stringify({ error: "No logs found for this service/worker" })); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 639 | return; |
| 640 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 641 | resp.status(200); |
| 642 | resp.write(JSON.stringify({ logs: serviceLog })); |
| 643 | } catch (e) { |
| 644 | console.log(e); |
| 645 | resp.status(500); |
| 646 | resp.write(JSON.stringify({ error: "Failed to get service logs" })); |
| 647 | } finally { |
| 648 | resp.end(); |
| 649 | } |
| 650 | }; |
| 651 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 652 | const handleRegisterWorker: express.Handler = async (req, resp) => { |
| 653 | try { |
| 654 | const projectId = Number(req.params["projectId"]); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 655 | const result = WorkerSchema.safeParse(req.body); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 656 | if (!result.success) { |
| 657 | resp.status(400); |
| 658 | resp.write( |
| 659 | JSON.stringify({ |
| 660 | error: "Invalid request data", |
| 661 | details: result.error.format(), |
| 662 | }), |
| 663 | ); |
| 664 | return; |
| 665 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 666 | let monitor = projectMonitors.get(projectId); |
| 667 | if (!monitor) { |
| 668 | monitor = new ProjectMonitor(); |
| 669 | projectMonitors.set(projectId, monitor); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 670 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 671 | monitor.registerWorker(result.data); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 672 | resp.status(200); |
| 673 | resp.write( |
| 674 | JSON.stringify({ |
| 675 | success: true, |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 676 | }), |
| 677 | ); |
| 678 | } catch (e) { |
| 679 | console.log(e); |
| 680 | resp.status(500); |
| 681 | resp.write(JSON.stringify({ error: "Failed to register worker" })); |
| 682 | } finally { |
| 683 | resp.end(); |
| 684 | } |
| 685 | }; |
| 686 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 687 | async function reloadProject(projectId: number): Promise<boolean> { |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 688 | const monitor = projectMonitors.get(projectId); |
| 689 | const projectWorkers = monitor ? monitor.getWorkerAddresses() : []; |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 690 | const workerCount = projectWorkers.length; |
| 691 | if (workerCount === 0) { |
| 692 | return true; |
| 693 | } |
| 694 | const results = await Promise.all( |
| 695 | projectWorkers.map(async (workerAddress) => { |
| 696 | const resp = await axios.post(`${workerAddress}/update`); |
| 697 | return resp.status === 200; |
| 698 | }), |
| 699 | ); |
| 700 | return results.reduce((acc, curr) => acc && curr, true); |
| 701 | } |
| 702 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 703 | const handleReload: express.Handler = async (req, resp) => { |
| 704 | try { |
| 705 | const projectId = Number(req.params["projectId"]); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 706 | const projectAuth = await db.project.findFirst({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 707 | where: { |
| 708 | id: projectId, |
| 709 | userId: resp.locals.userId, |
| 710 | }, |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 711 | select: { id: true }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 712 | }); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 713 | if (!projectAuth) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 714 | resp.status(404); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 715 | return; |
| 716 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 717 | const success = await reloadProject(projectId); |
| 718 | if (success) { |
| 719 | resp.status(200); |
| 720 | } else { |
| 721 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 722 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 723 | } catch (e) { |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 724 | console.error(e); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 725 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 726 | } |
| 727 | }; |
| 728 | |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 729 | const handleReloadWorker: express.Handler = async (req, resp) => { |
| 730 | const projectId = Number(req.params["projectId"]); |
| 731 | const serviceName = req.params["serviceName"]; |
| 732 | const workerId = req.params["workerId"]; |
| 733 | |
| 734 | const projectMonitor = projectMonitors.get(projectId); |
| 735 | if (!projectMonitor) { |
| 736 | resp.status(404).send({ error: "Project monitor not found" }); |
| 737 | return; |
| 738 | } |
| 739 | |
| 740 | try { |
| 741 | await projectMonitor.reloadWorker(serviceName, workerId); |
| 742 | resp.status(200).send({ message: "Worker reload initiated" }); |
| 743 | } catch (error) { |
| 744 | console.error(`Failed to reload worker ${workerId} in service ${serviceName} for project ${projectId}:`, error); |
| 745 | const errorMessage = error instanceof Error ? error.message : "Unknown error"; |
| 746 | resp.status(500).send({ error: `Failed to reload worker: ${errorMessage}` }); |
| 747 | } |
| 748 | }; |
| 749 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 750 | const analyzeRepoReqSchema = z.object({ |
| 751 | address: z.string(), |
| 752 | }); |
| 753 | |
| 754 | const handleAnalyzeRepo: express.Handler = async (req, resp) => { |
| 755 | const projectId = Number(req.params["projectId"]); |
| 756 | const project = await db.project.findUnique({ |
| 757 | where: { |
| 758 | id: projectId, |
| 759 | userId: resp.locals.userId, |
| 760 | }, |
| 761 | select: { |
| 762 | githubToken: true, |
| 763 | deployKey: true, |
| 764 | deployKeyPublic: true, |
| 765 | }, |
| 766 | }); |
| 767 | if (!project) { |
| 768 | resp.status(404).send({ error: "Project not found" }); |
| 769 | return; |
| 770 | } |
| 771 | if (!project.githubToken) { |
| 772 | resp.status(400).send({ error: "GitHub token not configured" }); |
| 773 | return; |
| 774 | } |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame^] | 775 | let tmpDir: tmp.DirResult | null = null; |
| 776 | try { |
| 777 | let deployKey: string | null = project.deployKey; |
| 778 | let deployKeyPublic: string | null = project.deployKeyPublic; |
| 779 | if (!deployKeyPublic) { |
| 780 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 781 | await db.project.update({ |
| 782 | where: { id: projectId }, |
| 783 | data: { |
| 784 | deployKeyPublic: deployKeyPublic, |
| 785 | deployKey: deployKey, |
| 786 | }, |
| 787 | }); |
| 788 | } |
| 789 | const github = new GithubClient(project.githubToken); |
| 790 | const result = analyzeRepoReqSchema.safeParse(req.body); |
| 791 | if (!result.success) { |
| 792 | resp.status(400).send({ error: "Invalid request data" }); |
| 793 | return; |
| 794 | } |
| 795 | const { address } = result.data; |
| 796 | tmpDir = tmp.dirSync({ |
| 797 | unsafeCleanup: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 798 | }); |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame^] | 799 | await github.addDeployKey(address, deployKeyPublic); |
| 800 | await fs.promises.writeFile(path.join(tmpDir.name, "key"), deployKey!, { |
| 801 | mode: 0o600, |
| 802 | }); |
| 803 | shell.exec( |
| 804 | `GIT_SSH_COMMAND='ssh -i ${tmpDir.name}/key -o IdentitiesOnly=yes' git clone ${address} ${tmpDir.name}/code`, |
| 805 | ); |
| 806 | const fsc = new RealFileSystem(`${tmpDir.name}/code`); |
| 807 | const analyzer = new NodeJSAnalyzer(); |
| 808 | const info = await analyzer.analyze(fsc, "/"); |
| 809 | resp.status(200).send([info]); |
| 810 | } catch (e) { |
| 811 | console.error(e); |
| 812 | resp.status(500).send({ error: "Failed to analyze repository" }); |
| 813 | } finally { |
| 814 | if (tmpDir) { |
| 815 | tmpDir.removeCallback(); |
| 816 | } |
| 817 | resp.end(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 818 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 819 | }; |
| 820 | |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 821 | const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => { |
| 822 | const userId = req.get("x-forwarded-userid"); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 823 | const username = req.get("x-forwarded-user"); |
| 824 | if (userId == null || username == null) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 825 | resp.status(401); |
| 826 | resp.write("Unauthorized"); |
| 827 | resp.end(); |
| 828 | return; |
| 829 | } |
| 830 | resp.locals.userId = userId; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 831 | resp.locals.username = username; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 832 | next(); |
| 833 | }; |
| 834 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 835 | const handleGithubPushWebhook: express.Handler = async (req, resp) => { |
| 836 | try { |
| 837 | // TODO(gio): Implement GitHub signature verification for security |
| 838 | const webhookSchema = z.object({ |
| 839 | repository: z.object({ |
| 840 | ssh_url: z.string(), |
| 841 | }), |
| 842 | }); |
| 843 | |
| 844 | const result = webhookSchema.safeParse(req.body); |
| 845 | if (!result.success) { |
| 846 | console.warn("GitHub webhook: Invalid payload:", result.error.issues); |
| 847 | resp.status(400).json({ error: "Invalid webhook payload" }); |
| 848 | return; |
| 849 | } |
| 850 | const { ssh_url: addr } = result.data.repository; |
| 851 | const allProjects = await db.project.findMany({ |
| 852 | select: { |
| 853 | id: true, |
| 854 | state: true, |
| 855 | }, |
| 856 | where: { |
| 857 | instanceId: { |
| 858 | not: null, |
| 859 | }, |
| 860 | }, |
| 861 | }); |
| 862 | // TODO(gio): This should run in background |
| 863 | new Promise<boolean>((resolve, reject) => { |
| 864 | setTimeout(() => { |
| 865 | const projectsToReloadIds: number[] = []; |
| 866 | for (const project of allProjects) { |
| 867 | if (project.state && project.state.length > 0) { |
| 868 | const projectRepos = extractGithubRepos(project.state); |
| 869 | if (projectRepos.includes(addr)) { |
| 870 | projectsToReloadIds.push(project.id); |
| 871 | } |
| 872 | } |
| 873 | } |
| 874 | Promise.all(projectsToReloadIds.map((id) => reloadProject(id))) |
| 875 | .then((results) => { |
| 876 | resolve(results.reduce((acc, curr) => acc && curr, true)); |
| 877 | }) |
| 878 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 879 | .catch((reason: any) => reject(reason)); |
| 880 | }, 10); |
| 881 | }); |
| 882 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 883 | } catch (error: any) { |
| 884 | console.error(error); |
| 885 | resp.status(500); |
| 886 | } |
| 887 | }; |
| 888 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 889 | async function start() { |
| 890 | await db.$connect(); |
| 891 | const app = express(); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 892 | app.use(express.json()); // Global JSON parsing |
| 893 | |
| 894 | // Public webhook route - no auth needed |
| 895 | app.post("/api/webhook/github/push", handleGithubPushWebhook); |
| 896 | |
| 897 | // Authenticated project routes |
| 898 | const projectRouter = express.Router(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 899 | projectRouter.use(auth); |
| 900 | projectRouter.post("/:projectId/analyze", handleAnalyzeRepo); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 901 | projectRouter.post("/:projectId/saved", handleSave); |
| 902 | projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy")); |
| 903 | projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft")); |
| 904 | projectRouter.post("/:projectId/deploy", handleDeploy); |
| 905 | projectRouter.get("/:projectId/status", handleStatus); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 906 | projectRouter.delete("/:projectId", handleProjectDelete); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 907 | projectRouter.get("/:projectId/repos/github", handleGithubRepos); |
| 908 | projectRouter.post("/:projectId/github-token", handleUpdateGithubToken); |
| 909 | projectRouter.get("/:projectId/env", handleEnv); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 910 | projectRouter.post("/:projectId/reload/:serviceName/:workerId", handleReloadWorker); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 911 | projectRouter.post("/:projectId/reload", handleReload); |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 912 | projectRouter.get("/:projectId/logs/:service/:workerId", handleServiceLogs); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 913 | projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment); |
| 914 | projectRouter.get("/", handleProjectAll); |
| 915 | projectRouter.post("/", handleProjectCreate); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 916 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 917 | app.use("/api/project", projectRouter); // Mount the authenticated router |
| 918 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 919 | app.use("/", express.static("../front/dist")); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 920 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 921 | const internalApi = express(); |
| 922 | internalApi.use(express.json()); |
| 923 | internalApi.post("/api/project/:projectId/workers", handleRegisterWorker); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 924 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 925 | app.listen(env.DODO_PORT_WEB, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 926 | console.log("Web server started on port", env.DODO_PORT_WEB); |
| 927 | }); |
| 928 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 929 | internalApi.listen(env.DODO_PORT_API, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 930 | console.log("Internal API server started on port", env.DODO_PORT_API); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 931 | }); |
| 932 | } |
| 933 | |
| 934 | start(); |