From d81640878ae305e7b6b4ece4bd393acefeeb37c9 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:50:11 +0530 Subject: [PATCH 1/5] Add GitHub URL parsing and repository download client --- apps/backend/src/config/env.ts | 10 + apps/backend/src/github/github-url.ts | 100 ++++++++++ apps/backend/src/github/github.client.ts | 225 +++++++++++++++++++++++ apps/backend/src/github/github.errors.ts | 36 ++++ apps/backend/src/http/error-response.ts | 8 + 5 files changed, 379 insertions(+) create mode 100644 apps/backend/src/github/github-url.ts create mode 100644 apps/backend/src/github/github.client.ts create mode 100644 apps/backend/src/github/github.errors.ts diff --git a/apps/backend/src/config/env.ts b/apps/backend/src/config/env.ts index 94005e3..db648d0 100644 --- a/apps/backend/src/config/env.ts +++ b/apps/backend/src/config/env.ts @@ -30,6 +30,16 @@ const envSchema = z.object({ * 0 if the server is reached directly. */ TRUST_PROXY_HOPS: z.coerce.number().int().min(0).default(1), + /** + * Optional GitHub token for analyzing repositories by URL. Without it, + * GitHub allows 60 API requests per hour from the server's IP; with it, + * 5,000. A fine-grained token with no permissions is enough (public + * repositories only). + */ + GITHUB_TOKEN: z + .string() + .optional() + .transform((value) => value?.trim() || undefined), /** * Upper bound on the prompt size sent to Gemini. Source files are * ranked by importance and added until this budget is reached. diff --git a/apps/backend/src/github/github-url.ts b/apps/backend/src/github/github-url.ts new file mode 100644 index 0000000..7eb6f0d --- /dev/null +++ b/apps/backend/src/github/github-url.ts @@ -0,0 +1,100 @@ +import { GitHubError } from "./github.errors.js"; + +export interface GitHubRepositoryRef { + owner: string; + repo: string; + /** Branch, tag or commit from a /tree/ URL; default branch if absent. */ + ref?: string; +} + +/** + * GitHub's own limits: owners are letters, digits and single hyphens; + * repository names are letters, digits, '.', '-' and '_'. + */ +const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/; +const REPO = /^[A-Za-z0-9._-]{1,100}$/; +const REF = /^[A-Za-z0-9._\-/]{1,255}$/; + +const INVALID_MESSAGE = + "Enter a public GitHub repository, like https://github.com/owner/repo or owner/repo."; + +/** + * Parses what a user pastes into the GitHub URL field: + * + * https://github.com/owner/repo + * https://github.com/owner/repo.git + * https://github.com/owner/repo/tree/branch-or-tag + * github.com/owner/repo + * owner/repo + * + * Only github.com is accepted, and every part is validated against + * GitHub's naming rules, so the values are safe to put in API URLs. + */ +export function parseGitHubUrl(input: string): GitHubRepositoryRef { + let text = input.trim(); + + if (!text || text.length > 500) { + throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE); + } + + // "." and ".." segments would be silently resolved by URL parsing + // (github.com/a/b/../c → github.com/a/c): reject them instead. + if (/(^|\/)\.{1,2}(\/|$|[?#])/.test(text.replace(/^https?:\/\//i, ""))) { + throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE); + } + + let path: string; + + if (/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+\/?$/.test(text)) { + // owner/repo shorthand + path = text; + } else { + if (!/^https?:\/\//i.test(text)) { + text = `https://${text}`; + } + + let url: URL; + + try { + url = new URL(text); + } catch { + throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE); + } + + const host = url.hostname.toLowerCase(); + + if (host !== "github.com" && host !== "www.github.com") { + throw new GitHubError( + "INVALID_GITHUB_URL", + "Only github.com repositories are supported.", + ); + } + + path = decodeURIComponent(url.pathname); + } + + const segments = path.split("/").filter(Boolean); + + if (segments.length < 2) { + throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE); + } + + const owner = segments[0]; + const repo = segments[1].replace(/\.git$/i, ""); + + if (!OWNER.test(owner) || !REPO.test(repo) || repo === "." || repo === "..") { + throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE); + } + + let ref: string | undefined; + + if (segments[2] === "tree" && segments.length > 3) { + ref = segments.slice(3).join("/"); + + if (!REF.test(ref) || ref.split("/").some((part) => part === "..")) { + throw new GitHubError("INVALID_GITHUB_URL", "That branch name is not valid."); + } + } + + return { owner, repo, ref }; +} diff --git a/apps/backend/src/github/github.client.ts b/apps/backend/src/github/github.client.ts new file mode 100644 index 0000000..89f066f --- /dev/null +++ b/apps/backend/src/github/github.client.ts @@ -0,0 +1,225 @@ +import fs from "node:fs"; +import fsPromises from "node:fs/promises"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; + +import { env } from "../config/env.js"; +import { GitHubError } from "./github.errors.js"; +import type { GitHubRepositoryRef } from "./github-url.js"; + +const API = "https://api.github.com"; + +const METADATA_TIMEOUT_MS = 10_000; +const DOWNLOAD_TIMEOUT_MS = 120_000; + +/** + * Hosts a zipball download may end up on after GitHub's redirect. + */ +const ALLOWED_DOWNLOAD_HOSTS = new Set([ + "api.github.com", + "codeload.github.com", +]); + +export interface ResolvedRepository { + /** Canonical "owner/repo" as GitHub spells it. */ + fullName: string; + owner: string; + repo: string; + /** Branch, tag or commit that was requested (default branch if none). */ + ref: string; + /** Exact commit that will be analyzed. */ + commitSha: string; + htmlUrl: string; +} + +function headers(): Record { + return { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "RepoInsight-AI", + ...(env.GITHUB_TOKEN ? { Authorization: `Bearer ${env.GITHUB_TOKEN}` } : {}), + }; +} + +function encodePath(value: string): string { + return value.split("/").map(encodeURIComponent).join("/"); +} + +/** + * Turns a failed GitHub response into an error the user can act on. + */ +function toGitHubError(response: Response, notFound: GitHubError): GitHubError { + if (response.status === 404) { + return notFound; + } + + if ( + response.status === 429 || + (response.status === 403 && + response.headers.get("x-ratelimit-remaining") === "0") + ) { + return new GitHubError( + "GITHUB_RATE_LIMITED", + "GitHub's request limit for this server has been reached. Please try again later, or upload the repository as a ZIP.", + ); + } + + return new GitHubError( + "GITHUB_UNAVAILABLE", + `GitHub could not be reached (status ${response.status}). Please try again, or upload the repository as a ZIP.`, + ); +} + +async function githubFetch(url: string, timeoutMs: number): Promise { + try { + return await fetch(url, { + headers: headers(), + redirect: "follow", + signal: AbortSignal.timeout(timeoutMs), + }); + } catch { + throw new GitHubError( + "GITHUB_UNAVAILABLE", + "GitHub could not be reached. Please try again, or upload the repository as a ZIP.", + ); + } +} + +/** + * Looks up a public repository and the exact commit to analyze. + * Runs before a job is created, so problems are reported immediately. + */ +export async function resolveRepository( + target: GitHubRepositoryRef, +): Promise { + const repoPath = `${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}`; + + const notFound = new GitHubError( + "GITHUB_REPO_NOT_FOUND", + `Repository ${target.owner}/${target.repo} was not found. Only public repositories can be analyzed.`, + ); + + const repoResponse = await githubFetch(`${API}/repos/${repoPath}`, METADATA_TIMEOUT_MS); + + if (!repoResponse.ok) { + throw toGitHubError(repoResponse, notFound); + } + + const repository = (await repoResponse.json()) as { + full_name: string; + private: boolean; + default_branch: string; + html_url: string; + }; + + // A token could see private repositories; never analyze them. + if (repository.private) { + throw new GitHubError( + "GITHUB_REPO_PRIVATE", + "Private repositories cannot be analyzed by URL. Upload a ZIP instead.", + ); + } + + const ref = target.ref ?? repository.default_branch; + + const commitResponse = await githubFetch( + `${API}/repos/${repoPath}/commits/${encodePath(ref)}`, + METADATA_TIMEOUT_MS, + ); + + if (!commitResponse.ok) { + throw toGitHubError( + commitResponse, + new GitHubError( + "GITHUB_REF_NOT_FOUND", + `Branch, tag or commit "${ref}" was not found in ${repository.full_name}.`, + ), + ); + } + + const commit = (await commitResponse.json()) as { sha: string }; + + const [owner, repo] = repository.full_name.split("/"); + + return { + fullName: repository.full_name, + owner, + repo, + ref, + commitSha: commit.sha, + htmlUrl: repository.html_url, + }; +} + +/** + * Downloads the repository at the resolved commit as a ZIP. + * Stops (and deletes the partial file) if it exceeds `maxBytes`. + */ +export async function downloadRepositoryZip( + repository: ResolvedRepository, + destination: string, + maxBytes: number, +): Promise { + const response = await githubFetch( + `${API}/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/zipball/${repository.commitSha}`, + DOWNLOAD_TIMEOUT_MS, + ); + + if (!response.ok || !response.body) { + throw toGitHubError( + response, + new GitHubError( + "GITHUB_REPO_NOT_FOUND", + `Repository ${repository.fullName} is no longer available.`, + ), + ); + } + + if (!ALLOWED_DOWNLOAD_HOSTS.has(new URL(response.url).hostname)) { + throw new GitHubError( + "GITHUB_UNAVAILABLE", + "GitHub returned an unexpected download location.", + ); + } + + const tooLarge = new GitHubError( + "GITHUB_REPO_TOO_LARGE", + `${repository.fullName} is larger than the ${Math.round(maxBytes / 1024 / 1024)} MB download limit.`, + ); + + const declared = Number(response.headers.get("content-length")); + + if (declared > maxBytes) { + await response.body.cancel(); + throw tooLarge; + } + + let received = 0; + + const limit = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + received += chunk.length; + + callback(received > maxBytes ? tooLarge : null, chunk); + }, + }); + + try { + await pipeline( + Readable.fromWeb(response.body as import("node:stream/web").ReadableStream), + limit, + fs.createWriteStream(destination), + ); + } catch (error) { + await fsPromises.rm(destination, { force: true }); + + if (error instanceof GitHubError) { + throw error; + } + + throw new GitHubError( + "GITHUB_UNAVAILABLE", + "The download from GitHub was interrupted. Please try again.", + ); + } +} diff --git a/apps/backend/src/github/github.errors.ts b/apps/backend/src/github/github.errors.ts new file mode 100644 index 0000000..a5946b8 --- /dev/null +++ b/apps/backend/src/github/github.errors.ts @@ -0,0 +1,36 @@ +export type GitHubErrorCode = + | "INVALID_GITHUB_URL" + | "GITHUB_REPO_NOT_FOUND" + | "GITHUB_REPO_PRIVATE" + | "GITHUB_REF_NOT_FOUND" + | "GITHUB_REPO_TOO_LARGE" + | "GITHUB_RATE_LIMITED" + | "GITHUB_UNAVAILABLE"; + +const STATUS: Record = { + INVALID_GITHUB_URL: 400, + GITHUB_REPO_NOT_FOUND: 404, + GITHUB_REPO_PRIVATE: 403, + GITHUB_REF_NOT_FOUND: 404, + GITHUB_REPO_TOO_LARGE: 413, + GITHUB_RATE_LIMITED: 503, + GITHUB_UNAVAILABLE: 502, +}; + +/** + * A problem with a GitHub URL or with fetching the repository. + * The message is shown to the user as is. + */ +export class GitHubError extends Error { + readonly code: GitHubErrorCode; + + readonly status: number; + + constructor(code: GitHubErrorCode, message: string) { + super(message); + + this.name = "GitHubError"; + this.code = code; + this.status = STATUS[code]; + } +} diff --git a/apps/backend/src/http/error-response.ts b/apps/backend/src/http/error-response.ts index a138059..0c5366a 100644 --- a/apps/backend/src/http/error-response.ts +++ b/apps/backend/src/http/error-response.ts @@ -4,6 +4,7 @@ import { MAX_UPLOAD_SIZE } from "../constants/upload.js"; import { InvalidArchiveError } from "../repository/errors/InvalidArchiveError.js"; import { RepositoryTooLargeError } from "../repository/errors/RepositoryTooLargeError.js"; import type { JobError } from "../jobs/job.types.js"; +import { GitHubError } from "../github/github.errors.js"; export class CorsError extends Error {} @@ -51,6 +52,13 @@ export function toErrorResponse(err: unknown): JobError { }; } + if (err instanceof GitHubError) { + return { + status: err.status, + body: { success: false, error: err.code, message: err.message }, + }; + } + if (err instanceof CorsError) { return { status: 403, From d7aea5921ebcceafd9240ec093bc04251dc10334 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:50:11 +0530 Subject: [PATCH 2/5] Analyze public GitHub repositories by URL --- .../src/ai/analysis/ai-analysis.service.ts | 2 +- .../backend/src/ai/analysis/analysis.types.ts | 3 + .../backend/src/ai/report/markdown.service.ts | 21 ++++++ .../src/application/analysis-job.runner.ts | 69 +++++++++++++++++- .../repository-analysis.service.ts | 5 +- apps/backend/src/jobs/job.types.ts | 10 +++ .../src/progress/progress.constants.ts | 7 ++ apps/backend/src/progress/progress.types.ts | 1 + .../repository/metadata/metadata.service.ts | 3 +- .../repository-processor.service.ts | 3 +- apps/backend/src/routes/analyze.ts | 73 +++++++++++++++++-- apps/backend/src/types/repository-info.ts | 13 ++++ apps/backend/test/job-store.test.ts | 6 +- apps/backend/test/rate-limit.test.ts | 4 +- 14 files changed, 202 insertions(+), 18 deletions(-) create mode 100644 apps/backend/src/types/repository-info.ts diff --git a/apps/backend/src/ai/analysis/ai-analysis.service.ts b/apps/backend/src/ai/analysis/ai-analysis.service.ts index 16fe22f..1da13d3 100644 --- a/apps/backend/src/ai/analysis/ai-analysis.service.ts +++ b/apps/backend/src/ai/analysis/ai-analysis.service.ts @@ -150,7 +150,7 @@ export async function analyzeRepository( job.setStage("GENERATING_MARKDOWN"); - const markdown = buildMarkdown(report); + const markdown = buildMarkdown(report, request.repository); await job.logger.markdown(markdown); diff --git a/apps/backend/src/ai/analysis/analysis.types.ts b/apps/backend/src/ai/analysis/analysis.types.ts index b66e54a..edf75f3 100644 --- a/apps/backend/src/ai/analysis/analysis.types.ts +++ b/apps/backend/src/ai/analysis/analysis.types.ts @@ -1,9 +1,12 @@ import type { RepositoryMetadata } from "../../types/repository.js"; import type { EngineeringReport } from "../report/report.types.js"; import type { GenerationTrace } from "../trace/trace.types.js"; +import type { RepositoryInfo } from "../../types/repository-info.js"; export interface AnalysisRequest { metadata: RepositoryMetadata; + /** Shown in the Markdown report header. */ + repository?: RepositoryInfo; } export interface AnalysisResult { diff --git a/apps/backend/src/ai/report/markdown.service.ts b/apps/backend/src/ai/report/markdown.service.ts index 4100b20..31b49bf 100644 --- a/apps/backend/src/ai/report/markdown.service.ts +++ b/apps/backend/src/ai/report/markdown.service.ts @@ -1,3 +1,4 @@ +import type { RepositoryInfo } from "../../types/repository-info.js"; import type { EngineeringReport, EvidenceReference, @@ -36,6 +37,23 @@ function formatEvidence(evidence: EvidenceReference[]): string { return ["", "**Evidence**", "", ...items].join("\n"); } +/** + * "**Repository:** [owner/repo](url) · `main` @ `abc1234`" + */ +function formatRepositoryLine(repository: RepositoryInfo): string { + const name = repository.url + ? `[${repository.name}](${repository.url})` + : repository.name; + + const ref = repository.ref ? ` · \`${repository.ref}\`` : ""; + + const commit = repository.commitSha + ? ` @ \`${repository.commitSha.slice(0, 7)}\`` + : ""; + + return `**Repository:** ${name}${ref}${commit}`; +} + /** * Formats a bullet list. */ @@ -141,10 +159,13 @@ ${question.expectedAnswer} */ export function buildMarkdown( report: EngineeringReport, + repository?: RepositoryInfo, ): string { return [ "# AI Project Review", + ...(repository ? [formatRepositoryLine(repository)] : []), + "---", "## Project Summary", diff --git a/apps/backend/src/application/analysis-job.runner.ts b/apps/backend/src/application/analysis-job.runner.ts index 41d84a2..7c4c994 100644 --- a/apps/backend/src/application/analysis-job.runner.ts +++ b/apps/backend/src/application/analysis-job.runner.ts @@ -1,9 +1,66 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; + import { analyzeUploadedRepository } from "./repository-analysis.service.js"; import { jobStore } from "../jobs/job.store.js"; import { JobLogger } from "../logger/logger.service.js"; import { toErrorResponse } from "../http/error-response.js"; +import { downloadRepositoryZip } from "../github/github.client.js"; +import { MAX_UPLOAD_SIZE } from "../constants/upload.js"; + +import type { AnalysisSource, JobContext } from "../jobs/job.types.js"; +import type { RepositoryInfo } from "../types/repository-info.js"; + +const DOWNLOAD_DIRECTORY = "tmp/uploads"; + +/** + * Name shown in the report for an uploaded ZIP: its file name. + */ +function uploadName(fileName: string): string { + const name = path.basename(fileName).replace(/\.zip$/i, "").trim(); + + return (name || "repository").slice(0, 100); +} + +/** + * Gets the ZIP for a job: the uploaded file, or a fresh download + * of the resolved GitHub commit. + */ +async function prepareSource( + source: AnalysisSource, + context: JobContext, +): Promise<{ zipPath: string; repository: RepositoryInfo }> { + if (source.type === "upload") { + return { + zipPath: source.zipPath, + repository: { name: uploadName(source.fileName) }, + }; + } + + context.setStage("DOWNLOADING"); + + await fs.mkdir(DOWNLOAD_DIRECTORY, { recursive: true }); + + const zipPath = path.join(DOWNLOAD_DIRECTORY, `${randomUUID()}.zip`); -import type { JobContext } from "../jobs/job.types.js"; + await downloadRepositoryZip(source.repository, zipPath, MAX_UPLOAD_SIZE); + + await context.logger.info("Repository downloaded from GitHub", { + repository: source.repository.fullName, + commit: source.repository.commitSha, + }); + + return { + zipPath, + repository: { + name: source.repository.fullName, + url: source.repository.htmlUrl, + ref: source.repository.ref, + commitSha: source.repository.commitSha, + }, + }; +} /** * Runs one analysis job in the background and records the outcome @@ -11,7 +68,7 @@ import type { JobContext } from "../jobs/job.types.js"; */ export async function runAnalysisJob( jobId: string, - zipFilePath: string, + source: AnalysisSource, ): Promise { const logger = new JobLogger(jobId); @@ -22,13 +79,17 @@ export async function runAnalysisJob( }; try { - await logger.info("Repository analysis started"); + await logger.info("Repository analysis started", { source: source.type }); + + const { zipPath, repository } = await prepareSource(source, context); - const result = await analyzeUploadedRepository(zipFilePath, context); + // Deletes the ZIP and extracted files when done. + const result = await analyzeUploadedRepository(zipPath, context, repository); jobStore.complete(jobId, { report: result.report, markdown: result.markdown, + repository, }); await logger.info("Repository analysis completed", result.trace); diff --git a/apps/backend/src/application/repository-analysis.service.ts b/apps/backend/src/application/repository-analysis.service.ts index d703f87..e83c025 100644 --- a/apps/backend/src/application/repository-analysis.service.ts +++ b/apps/backend/src/application/repository-analysis.service.ts @@ -7,6 +7,7 @@ import { analyzeRepository } from "../ai/analysis/ai-analysis.service.js"; import type { AnalysisResult } from "../ai/analysis/analysis.types.js"; import type { JobContext } from "../jobs/job.types.js"; +import type { RepositoryInfo } from "../types/repository-info.js"; /** * Runs the full analysis for an uploaded ZIP. @@ -17,6 +18,7 @@ import type { JobContext } from "../jobs/job.types.js"; export async function analyzeUploadedRepository( zipFilePath: string, job: JobContext, + repository: RepositoryInfo, ): Promise { const extractionDirectory = await fs.mkdtemp( path.join(os.tmpdir(), "repository-"), @@ -27,9 +29,10 @@ export async function analyzeUploadedRepository( zipFilePath, extractionDirectory, job, + repository.name, ); - return await analyzeRepository({ metadata }, job); + return await analyzeRepository({ metadata, repository }, job); } finally { await Promise.allSettled([ fs.rm(extractionDirectory, { diff --git a/apps/backend/src/jobs/job.types.ts b/apps/backend/src/jobs/job.types.ts index 9aaf062..ad59e48 100644 --- a/apps/backend/src/jobs/job.types.ts +++ b/apps/backend/src/jobs/job.types.ts @@ -1,4 +1,6 @@ import type { EngineeringReport } from "../ai/report/report.types.js"; +import type { ResolvedRepository } from "../github/github.client.js"; +import type { RepositoryInfo } from "../types/repository-info.js"; import type { JobLogger } from "../logger/logger.service.js"; import type { AnalysisProgress, @@ -10,8 +12,16 @@ export type JobStatus = "running" | "completed" | "failed"; export interface JobResult { report: EngineeringReport; markdown: string; + repository: RepositoryInfo; } +/** + * Where the repository for a job comes from. + */ +export type AnalysisSource = + | { type: "upload"; zipPath: string; fileName: string } + | { type: "github"; repository: ResolvedRepository }; + /** * Same shape as the HTTP error responses, so the frontend * handles synchronous and background failures identically. diff --git a/apps/backend/src/progress/progress.constants.ts b/apps/backend/src/progress/progress.constants.ts index 45e9e0f..21d82f1 100644 --- a/apps/backend/src/progress/progress.constants.ts +++ b/apps/backend/src/progress/progress.constants.ts @@ -21,6 +21,13 @@ export const ANALYSIS_PROGRESS: Record< updatedAt: Date.now(), }, + DOWNLOADING: { + stage: "DOWNLOADING", + message: "Downloading repository from GitHub...", + percentage: 10, + updatedAt: Date.now(), + }, + EXTRACTING: { stage: "EXTRACTING", message: "Extracting ZIP archive...", diff --git a/apps/backend/src/progress/progress.types.ts b/apps/backend/src/progress/progress.types.ts index faed9b7..62d89ce 100644 --- a/apps/backend/src/progress/progress.types.ts +++ b/apps/backend/src/progress/progress.types.ts @@ -7,6 +7,7 @@ export type AnalysisStage = | "IDLE" | "UPLOADING" + | "DOWNLOADING" | "EXTRACTING" | "READING_REPOSITORY" | "BUILDING_METADATA" diff --git a/apps/backend/src/repository/metadata/metadata.service.ts b/apps/backend/src/repository/metadata/metadata.service.ts index d7eb708..587e0cf 100644 --- a/apps/backend/src/repository/metadata/metadata.service.ts +++ b/apps/backend/src/repository/metadata/metadata.service.ts @@ -162,6 +162,7 @@ function detectFrameworks( export function buildRepositoryMetadata( repository: RepositoryContent, tree: RepositoryTree, + displayName?: string, ): RepositoryMetadata { const files = repository.files; @@ -188,7 +189,7 @@ export function buildRepositoryMetadata( .sort(); const repositoryName = - path.basename(repository.rootPath); + displayName ?? path.basename(repository.rootPath); const metrics = buildRepositoryMetrics( repository, diff --git a/apps/backend/src/repository/repository-processor.service.ts b/apps/backend/src/repository/repository-processor.service.ts index 698cff2..56b532c 100644 --- a/apps/backend/src/repository/repository-processor.service.ts +++ b/apps/backend/src/repository/repository-processor.service.ts @@ -11,6 +11,7 @@ export async function processRepository( zipFilePath: string, extractionDirectory: string, job: JobContext, + displayName?: string, ): Promise { job.setStage("EXTRACTING"); @@ -36,7 +37,7 @@ export async function processRepository( job.setStage("STATIC_ANALYSIS"); - const metadata = buildRepositoryMetadata(content, tree); + const metadata = buildRepositoryMetadata(content, tree, displayName); await job.logger.info("Repository metadata generated"); diff --git a/apps/backend/src/routes/analyze.ts b/apps/backend/src/routes/analyze.ts index 0615605..9880276 100644 --- a/apps/backend/src/routes/analyze.ts +++ b/apps/backend/src/routes/analyze.ts @@ -1,14 +1,29 @@ import fs from "node:fs/promises"; -import { Router } from "express"; +import { Router, type Response } from "express"; import { upload } from "../http/multer.js"; import { analysisRateLimits } from "../http/rate-limit.js"; import { runAnalysisJob } from "../application/analysis-job.runner.js"; import { jobStore } from "../jobs/job.store.js"; import { env } from "../config/env.js"; +import { parseGitHubUrl } from "../github/github-url.js"; +import { resolveRepository } from "../github/github.client.js"; const router = Router(); +function isBusy(): boolean { + return jobStore.runningCount() >= env.MAX_CONCURRENT_JOBS; +} + +function sendBusy(res: Response) { + return res.status(429).json({ + success: false, + error: "SERVER_BUSY", + message: + "The server is busy with other analyses. Please try again in a minute.", + }); +} + /** * Accepts a ZIP upload and starts a background analysis job. * @@ -29,24 +44,68 @@ router.post( }); } - if (jobStore.runningCount() >= env.MAX_CONCURRENT_JOBS) { + if (isBusy()) { await fs.rm(req.file.path, { force: true }); - return res.status(429).json({ + return sendBusy(res); + } + + const job = jobStore.create(); + + void runAnalysisJob(job.id, { + type: "upload", + zipPath: req.file.path, + fileName: req.file.originalname, + }); + + return res.status(202).json({ + success: true, + jobId: job.id, + }); + }, +); + +/** + * Starts a background analysis of a public GitHub repository. + * Body: { "url": "https://github.com/owner/repo" } + * + * The URL is checked and the repository looked up on GitHub before the + * job is created, so mistakes (typos, private repositories) are reported + * immediately and do not count toward the rate limit. The download + * itself happens inside the job. + */ +router.post( + "/analyze/github", + ...analysisRateLimits, + async (req, res) => { + const url: unknown = req.body?.url; + + if (typeof url !== "string") { + return res.status(400).json({ success: false, - error: "SERVER_BUSY", - message: - "The server is busy with other analyses. Please try again in a minute.", + error: "INVALID_GITHUB_URL", + message: 'Send a JSON body like { "url": "https://github.com/owner/repo" }.', }); } + if (isBusy()) { + return sendBusy(res); + } + + // Throws GitHubError, which the error handler turns into JSON. + const repository = await resolveRepository(parseGitHubUrl(url)); + const job = jobStore.create(); - void runAnalysisJob(job.id, req.file.path); + void runAnalysisJob(job.id, { type: "github", repository }); return res.status(202).json({ success: true, jobId: job.id, + repository: { + name: repository.fullName, + commitSha: repository.commitSha, + }, }); }, ); diff --git a/apps/backend/src/types/repository-info.ts b/apps/backend/src/types/repository-info.ts new file mode 100644 index 0000000..9322b13 --- /dev/null +++ b/apps/backend/src/types/repository-info.ts @@ -0,0 +1,13 @@ +/** + * Which repository a report is about, shown in the report header. + */ +export interface RepositoryInfo { + /** "owner/repo" for GitHub, the ZIP's file name for uploads. */ + name: string; + /** Link to the repository (GitHub only). */ + url?: string; + /** Branch, tag or commit that was requested (GitHub only). */ + ref?: string; + /** Exact commit analyzed (GitHub only). */ + commitSha?: string; +} diff --git a/apps/backend/test/job-store.test.ts b/apps/backend/test/job-store.test.ts index f6a9709..232a74a 100644 --- a/apps/backend/test/job-store.test.ts +++ b/apps/backend/test/job-store.test.ts @@ -33,7 +33,11 @@ describe("jobStore", () => { it("does not change a job after it has finished", () => { const job = jobStore.create(); - jobStore.complete(job.id, { report, markdown: "# done" }); + jobStore.complete(job.id, { + report, + markdown: "# done", + repository: { name: "demo" }, + }); jobStore.fail(job.id, { status: 500, body: { success: false, error: "X", message: "late failure" }, diff --git a/apps/backend/test/rate-limit.test.ts b/apps/backend/test/rate-limit.test.ts index 4e84fe4..f83af5a 100644 --- a/apps/backend/test/rate-limit.test.ts +++ b/apps/backend/test/rate-limit.test.ts @@ -14,8 +14,8 @@ process.env.MAX_CONCURRENT_JOBS = "100"; // Never run a real analysis: just delete the uploaded file. vi.mock("../src/application/analysis-job.runner.js", () => ({ - runAnalysisJob: vi.fn(async (_jobId: string, zipPath: string) => { - await fs.rm(zipPath, { force: true }); + runAnalysisJob: vi.fn(async (_jobId: string, source: { zipPath?: string }) => { + if (source.zipPath) await fs.rm(source.zipPath, { force: true }); }), })); From 7b98e7b847d7c78a7a7537dea05a238ff88f31e7 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:50:11 +0530 Subject: [PATCH 3/5] Test GitHub URL parsing, client, route and jobs --- apps/backend/test/github-client.test.ts | 201 ++++++++++++++++++++++++ apps/backend/test/github-job.test.ts | 106 +++++++++++++ apps/backend/test/github-route.test.ts | 106 +++++++++++++ apps/backend/test/github-url.test.ts | 46 ++++++ 4 files changed, 459 insertions(+) create mode 100644 apps/backend/test/github-client.test.ts create mode 100644 apps/backend/test/github-job.test.ts create mode 100644 apps/backend/test/github-route.test.ts create mode 100644 apps/backend/test/github-url.test.ts diff --git a/apps/backend/test/github-client.test.ts b/apps/backend/test/github-client.test.ts new file mode 100644 index 0000000..f2955a7 --- /dev/null +++ b/apps/backend/test/github-client.test.ts @@ -0,0 +1,201 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + downloadRepositoryZip, + resolveRepository, + type ResolvedRepository, +} from "../src/github/github.client.js"; +import { GitHubError } from "../src/github/github.errors.js"; +import { tempDir } from "./helpers/zip.js"; + +function json(status: number, body: unknown, headers: Record = {}) { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json", ...headers }, + }); +} + +function download(bytes: Uint8Array, url: string, headers: Record = {}) { + const response = new Response(new Uint8Array(bytes), { status: 200, headers }); + + // Response.url is set by fetch after redirects; fake it here. + Object.defineProperty(response, "url", { value: url }); + + return response; +} + +const repoResponse = { + full_name: "Owner/Repo", + private: false, + default_branch: "main", + html_url: "https://github.com/Owner/Repo", +}; + +const resolved: ResolvedRepository = { + fullName: "Owner/Repo", + owner: "Owner", + repo: "Repo", + ref: "main", + commitSha: "a".repeat(40), + htmlUrl: "https://github.com/Owner/Repo", +}; + +function mockFetch(...responses: Response[]) { + const fetchMock = vi.fn(); + + for (const response of responses) { + fetchMock.mockResolvedValueOnce(response); + } + + vi.stubGlobal("fetch", fetchMock); + + return fetchMock; +} + +async function expectGitHubError(promise: Promise, code: string) { + const error = await promise.catch((e: unknown) => e); + + expect(error).toBeInstanceOf(GitHubError); + expect((error as GitHubError).code).toBe(code); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("resolveRepository", () => { + it("resolves the default branch to an exact commit", async () => { + const fetchMock = mockFetch( + json(200, repoResponse), + json(200, { sha: "b".repeat(40) }), + ); + + const result = await resolveRepository({ owner: "owner", repo: "repo" }); + + expect(result).toEqual({ + fullName: "Owner/Repo", + owner: "Owner", + repo: "Repo", + ref: "main", + commitSha: "b".repeat(40), + htmlUrl: "https://github.com/Owner/Repo", + }); + expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ + "https://api.github.com/repos/owner/repo", + "https://api.github.com/repos/owner/repo/commits/main", + ]); + }); + + it("keeps slashes in branch names", async () => { + const fetchMock = mockFetch(json(200, repoResponse), json(200, { sha: "c".repeat(40) })); + + await resolveRepository({ owner: "owner", repo: "repo", ref: "feature/login" }); + + expect(fetchMock.mock.calls[1][0]).toBe( + "https://api.github.com/repos/owner/repo/commits/feature/login", + ); + }); + + it("reports missing repositories", async () => { + mockFetch(json(404, { message: "Not Found" })); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "missing" }), + "GITHUB_REPO_NOT_FOUND", + ); + }); + + it("refuses private repositories even when the token can see them", async () => { + mockFetch(json(200, { ...repoResponse, private: true })); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "repo" }), + "GITHUB_REPO_PRIVATE", + ); + }); + + it("reports unknown branches", async () => { + mockFetch(json(200, repoResponse), json(422, { message: "No commit found" })); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "repo", ref: "nope" }), + "GITHUB_UNAVAILABLE", + ); + + mockFetch(json(200, repoResponse), json(404, { message: "Not Found" })); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "repo", ref: "nope" }), + "GITHUB_REF_NOT_FOUND", + ); + }); + + it("explains GitHub's rate limit", async () => { + mockFetch(json(403, { message: "API rate limit exceeded" }, { "x-ratelimit-remaining": "0" })); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "repo" }), + "GITHUB_RATE_LIMITED", + ); + }); + + it("reports network failures", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("fetch failed"))); + + await expectGitHubError( + resolveRepository({ owner: "owner", repo: "repo" }), + "GITHUB_UNAVAILABLE", + ); + }); +}); + +describe("downloadRepositoryZip", () => { + it("downloads the exact commit to a file", async () => { + const fetchMock = mockFetch( + download(new Uint8Array([1, 2, 3]), "https://codeload.github.com/Owner/Repo/legacy.zip/abc"), + ); + const target = path.join(await tempDir(), "repo.zip"); + + await downloadRepositoryZip(resolved, target, 1000); + + expect(fetchMock.mock.calls[0][0]).toBe( + `https://api.github.com/repos/Owner/Repo/zipball/${"a".repeat(40)}`, + ); + expect([...(await fs.readFile(target))]).toEqual([1, 2, 3]); + }); + + it("stops and deletes the file when the download exceeds the limit", async () => { + mockFetch( + download(new Uint8Array(2000), "https://codeload.github.com/Owner/Repo/legacy.zip/abc"), + ); + const target = path.join(await tempDir(), "repo.zip"); + + await expectGitHubError( + downloadRepositoryZip(resolved, target, 1000), + "GITHUB_REPO_TOO_LARGE", + ); + await expect(fs.stat(target)).rejects.toThrow(); + }); + + it("rejects early when GitHub declares a size over the limit", async () => { + mockFetch( + download(new Uint8Array(10), "https://codeload.github.com/x", { "content-length": "5000" }), + ); + + await expectGitHubError( + downloadRepositoryZip(resolved, path.join(await tempDir(), "repo.zip"), 1000), + "GITHUB_REPO_TOO_LARGE", + ); + }); + + it("refuses downloads redirected outside GitHub", async () => { + mockFetch(download(new Uint8Array(10), "https://evil.example/repo.zip")); + + await expectGitHubError( + downloadRepositoryZip(resolved, path.join(await tempDir(), "repo.zip"), 1000), + "GITHUB_UNAVAILABLE", + ); + }); +}); diff --git a/apps/backend/test/github-job.test.ts b/apps/backend/test/github-job.test.ts new file mode 100644 index 0000000..e08d14b --- /dev/null +++ b/apps/backend/test/github-job.test.ts @@ -0,0 +1,106 @@ +import fs from "node:fs/promises"; +import { describe, expect, it, vi } from "vitest"; + +import { createZip } from "./helpers/zip.js"; + +vi.mock("../src/ai/gemini/gemini.client.js", () => ({ + generateContent: vi.fn(), +})); + +vi.mock("../src/github/github.client.js", () => ({ + resolveRepository: vi.fn(), + downloadRepositoryZip: vi.fn(), +})); + +const { generateContent } = await import("../src/ai/gemini/gemini.client.js"); +const { downloadRepositoryZip } = await import("../src/github/github.client.js"); +const { runAnalysisJob } = await import("../src/application/analysis-job.runner.js"); +const { jobStore } = await import("../src/jobs/job.store.js"); + +const report = { + summary: { purpose: "p", description: "d" }, + technologyStack: { languages: [], frameworks: [], databases: [], tools: [], infrastructure: [] }, + architecture: { summary: "s", strengths: [], weaknesses: [], scalability: "x", maintainability: "y" }, + folderStructure: { score: 7, positives: [], negatives: [], recommendations: [] }, + codeQuality: { score: 7, positives: [], negatives: [], recommendations: [] }, + strengths: [], + weaknesses: [], + improvements: [], + resumeFeedback: { score: 7, summary: "s", strengths: [], improvements: [], bestResumeBullets: [] }, + interviewQuestions: [], +}; + +const repository = { + fullName: "Owner/Repo", + owner: "Owner", + repo: "Repo", + ref: "main", + commitSha: "e".repeat(40), + htmlUrl: "https://github.com/Owner/Repo", +}; + +describe("GitHub analysis job", () => { + it("downloads, analyzes and labels the report with the repository and commit", async () => { + // GitHub zipballs wrap everything in "--/". + const fixture = await createZip([ + { name: "Owner-Repo-eeeeeee/src/index.ts", content: "export const a = 1;\n" }, + ]); + + vi.mocked(downloadRepositoryZip).mockImplementation(async (_repo, destination) => { + await fs.copyFile(fixture, destination); + }); + vi.mocked(generateContent).mockResolvedValue({ text: JSON.stringify(report) }); + + const job = jobStore.create(); + const stages: string[] = []; + const unsubscribe = jobStore.subscribe(job.id, (current) => { + stages.push(current.progress.stage); + }); + + await runAnalysisJob(job.id, { type: "github", repository }); + unsubscribe(); + + const result = jobStore.get(job.id); + + expect(result?.status).toBe("completed"); + expect(result?.result?.repository).toEqual({ + name: "Owner/Repo", + url: "https://github.com/Owner/Repo", + ref: "main", + commitSha: "e".repeat(40), + }); + expect(result?.result?.markdown).toContain( + "**Repository:** [Owner/Repo](https://github.com/Owner/Repo) · `main` @ `eeeeeee`", + ); + expect(stages[0]).toBe("DOWNLOADING"); + + // The prompt names the repository, not the temp folder. + const prompt = vi.mocked(generateContent).mock.calls[0][0]; + expect(prompt.userInstruction).toContain("Name: Owner/Repo"); + + // The downloaded ZIP is deleted afterwards. + const destination = vi.mocked(downloadRepositoryZip).mock.calls[0][1]; + await expect(fs.stat(destination)).rejects.toThrow(); + }); + + it("fails the job with GitHub's error when the download fails", async () => { + const { GitHubError } = await import("../src/github/github.errors.js"); + + vi.mocked(downloadRepositoryZip).mockRejectedValueOnce( + new GitHubError("GITHUB_REPO_TOO_LARGE", "Owner/Repo is larger than the 500 MB download limit."), + ); + + const job = jobStore.create(); + + await runAnalysisJob(job.id, { type: "github", repository }); + + expect(jobStore.get(job.id)?.error).toEqual({ + status: 413, + body: { + success: false, + error: "GITHUB_REPO_TOO_LARGE", + message: "Owner/Repo is larger than the 500 MB download limit.", + }, + }); + }); +}); diff --git a/apps/backend/test/github-route.test.ts b/apps/backend/test/github-route.test.ts new file mode 100644 index 0000000..6046118 --- /dev/null +++ b/apps/backend/test/github-route.test.ts @@ -0,0 +1,106 @@ +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +process.env.RATE_LIMIT_PER_HOUR = "1"; +process.env.RATE_LIMIT_PER_DAY = "0"; +process.env.MAX_CONCURRENT_JOBS = "100"; + +vi.mock("../src/application/analysis-job.runner.js", () => ({ + runAnalysisJob: vi.fn(async () => {}), +})); + +vi.mock("../src/github/github.client.js", () => ({ + resolveRepository: vi.fn(), + downloadRepositoryZip: vi.fn(), +})); + +const { default: app } = await import("../src/app.js"); +const { resolveRepository } = await import("../src/github/github.client.js"); +const { runAnalysisJob } = await import("../src/application/analysis-job.runner.js"); +const { GitHubError } = await import("../src/github/github.errors.js"); + +const resolveMock = vi.mocked(resolveRepository); + +let server: Server; +let baseUrl: string; + +beforeAll(async () => { + server = app.listen(0); + await new Promise((resolve) => server.once("listening", resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(() => { + server.close(); +}); + +async function analyze(body: unknown) { + const response = await fetch(`${baseUrl}/api/analyze/github`, { + method: "POST", + headers: { "Content-Type": "application/json", "X-Forwarded-For": "203.0.113.9" }, + body: JSON.stringify(body), + }); + + return { + status: response.status, + body: (await response.json()) as Record, + }; +} + +describe("POST /api/analyze/github", () => { + it("rejects a missing or invalid URL without calling GitHub", async () => { + expect((await analyze({})).status).toBe(400); + + const invalid = await analyze({ url: "https://gitlab.com/a/b" }); + + expect(invalid.status).toBe(400); + expect(invalid.body.error).toBe("INVALID_GITHUB_URL"); + expect(resolveMock).not.toHaveBeenCalled(); + }); + + it("reports repositories GitHub cannot find", async () => { + resolveMock.mockRejectedValueOnce( + new GitHubError("GITHUB_REPO_NOT_FOUND", "Repository a/b was not found."), + ); + + const missing = await analyze({ url: "a/b" }); + + expect(missing.status).toBe(404); + expect(missing.body).toMatchObject({ + error: "GITHUB_REPO_NOT_FOUND", + message: "Repository a/b was not found.", + }); + }); + + it("starts a job for a valid repository (errors above did not use the limit)", async () => { + const repository = { + fullName: "Owner/Repo", + owner: "Owner", + repo: "Repo", + ref: "main", + commitSha: "d".repeat(40), + htmlUrl: "https://github.com/Owner/Repo", + }; + resolveMock.mockResolvedValueOnce(repository); + + const started = await analyze({ url: "https://github.com/owner/repo" }); + + expect(started.status).toBe(202); + expect(started.body).toMatchObject({ + success: true, + repository: { name: "Owner/Repo", commitSha: "d".repeat(40) }, + }); + expect(vi.mocked(runAnalysisJob)).toHaveBeenCalledWith( + started.body.jobId, + { type: "github", repository }, + ); + }); + + it("applies the same per-visitor rate limit as uploads", async () => { + const limited = await analyze({ url: "owner/repo" }); + + expect(limited.status).toBe(429); + expect(limited.body.error).toBe("RATE_LIMITED"); + }); +}); diff --git a/apps/backend/test/github-url.test.ts b/apps/backend/test/github-url.test.ts new file mode 100644 index 0000000..4df663a --- /dev/null +++ b/apps/backend/test/github-url.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest"; + +import { parseGitHubUrl } from "../src/github/github-url.js"; +import { GitHubError } from "../src/github/github.errors.js"; + +describe("parseGitHubUrl", () => { + it.each([ + ["https://github.com/AtulBoyal/RepoInsight-AI", undefined], + ["https://github.com/AtulBoyal/RepoInsight-AI/", undefined], + ["https://github.com/AtulBoyal/RepoInsight-AI.git", undefined], + ["http://www.github.com/AtulBoyal/RepoInsight-AI", undefined], + ["github.com/AtulBoyal/RepoInsight-AI", undefined], + ["AtulBoyal/RepoInsight-AI", undefined], + [" https://github.com/AtulBoyal/RepoInsight-AI ", undefined], + ["https://github.com/AtulBoyal/RepoInsight-AI/tree/main", "main"], + ["https://github.com/AtulBoyal/RepoInsight-AI/tree/feature/login", "feature/login"], + ["https://github.com/AtulBoyal/RepoInsight-AI?tab=readme", undefined], + ])("accepts %s", (input, ref) => { + expect(parseGitHubUrl(input)).toEqual({ + owner: "AtulBoyal", + repo: "RepoInsight-AI", + ref, + }); + }); + + it("ignores pages inside a repository other than /tree/", () => { + expect( + parseGitHubUrl("https://github.com/owner/repo/issues/12"), + ).toEqual({ owner: "owner", repo: "repo", ref: undefined }); + }); + + it.each([ + "", + "https://gitlab.com/owner/repo", + "https://github.com.evil.example/owner/repo", + "https://github.com/owner", + "https://github.com/../etc/passwd", + "https://github.com/owner/repo/tree/../../x", + "https://github.com/-bad/repo", + "https://github.com/owner/re po", + "not a url at all", + "file:///etc/passwd", + ])("rejects %j", (input) => { + expect(() => parseGitHubUrl(input)).toThrow(GitHubError); + }); +}); From 1bd5da564aea281bd52b8f5bdc4bd86c00074b42 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:50:11 +0530 Subject: [PATCH 4/5] Add GitHub URL option and show analyzed repository in reports --- .../components/progress/CurrentStageCard.tsx | 4 +- .../src/components/progress/StageTimeline.tsx | 4 +- .../src/components/progress/progressStages.ts | 13 +++- .../src/components/report/ReportViewer.tsx | 27 +++++++- .../components/status/AnalysisProgress.tsx | 7 +- .../src/components/upload/GitHubUrlInput.tsx | 64 +++++++++++++++++++ .../src/components/upload/SourceToggle.tsx | 48 ++++++++++++++ apps/frontend/src/hooks/useAnalysis.ts | 55 +++++++++++++++- apps/frontend/src/pages/HomePage.tsx | 60 ++++++++++++----- apps/frontend/src/services/api.ts | 15 +++++ apps/frontend/src/types/progress.ts | 1 + apps/frontend/src/types/report.ts | 12 ++++ 12 files changed, 281 insertions(+), 29 deletions(-) create mode 100644 apps/frontend/src/components/upload/GitHubUrlInput.tsx create mode 100644 apps/frontend/src/components/upload/SourceToggle.tsx diff --git a/apps/frontend/src/components/progress/CurrentStageCard.tsx b/apps/frontend/src/components/progress/CurrentStageCard.tsx index c1becb0..94a73f9 100644 --- a/apps/frontend/src/components/progress/CurrentStageCard.tsx +++ b/apps/frontend/src/components/progress/CurrentStageCard.tsx @@ -1,4 +1,4 @@ -import { STAGES } from "./progressStages"; +import { STAGES, stageKey } from "./progressStages"; interface Props { stage: string; @@ -8,7 +8,7 @@ export default function CurrentStageCard({ stage, }: Props) { const current = - STAGES.find((item) => item.key === stage) ?? + STAGES.find((item) => item.key === stageKey(stage)) ?? STAGES[0]; const Icon = current.icon; diff --git a/apps/frontend/src/components/progress/StageTimeline.tsx b/apps/frontend/src/components/progress/StageTimeline.tsx index 0c25bfd..060d4ac 100644 --- a/apps/frontend/src/components/progress/StageTimeline.tsx +++ b/apps/frontend/src/components/progress/StageTimeline.tsx @@ -3,7 +3,7 @@ import { LoaderCircle, } from "lucide-react"; -import { STAGES } from "./progressStages"; +import { STAGES, stageKey } from "./progressStages"; interface Props { stage: string; @@ -14,7 +14,7 @@ export default function StageTimeline({ }: Props) { const currentIndex = STAGES.findIndex( - (item) => item.key === stage, + (item) => item.key === stageKey(stage), ); const visibleStages = STAGES.filter( diff --git a/apps/frontend/src/components/progress/progressStages.ts b/apps/frontend/src/components/progress/progressStages.ts index 357dd35..bc5bc6b 100644 --- a/apps/frontend/src/components/progress/progressStages.ts +++ b/apps/frontend/src/components/progress/progressStages.ts @@ -13,8 +13,8 @@ import { export const STAGES = [ { key: "UPLOADING", - title: "Uploading Repository", - description: "Uploading repository archive.", + title: "Getting Repository", + description: "Uploading your ZIP or downloading it from GitHub.", icon: Upload, }, { @@ -71,4 +71,11 @@ export const STAGES = [ description: "Engineering review completed.", icon: CheckCircle, }, -] as const; \ No newline at end of file +] as const; + +/** + * Downloading from GitHub is shown as the same first step as uploading. + */ +export function stageKey(stage: string): string { + return stage === "DOWNLOADING" ? "UPLOADING" : stage; +} diff --git a/apps/frontend/src/components/report/ReportViewer.tsx b/apps/frontend/src/components/report/ReportViewer.tsx index 74da0da..debaf3a 100644 --- a/apps/frontend/src/components/report/ReportViewer.tsx +++ b/apps/frontend/src/components/report/ReportViewer.tsx @@ -20,7 +20,7 @@ interface Props { export default function ReportViewer({ result, }: Props) { - const { report, markdown } = result; + const { report, markdown, repository } = result; return (
@@ -34,7 +34,30 @@ export default function ReportViewer({

- Generated by RepoInsight-AI + {repository.url ? ( + + {repository.name} + + ) : ( + + {repository.name} + + )} + {repository.ref && <> · {repository.ref}} + {repository.commitSha && ( + <> + {" @ "} + + {repository.commitSha.slice(0, 7)} + + + )} + {" · Generated by RepoInsight-AI"}

diff --git a/apps/frontend/src/components/status/AnalysisProgress.tsx b/apps/frontend/src/components/status/AnalysisProgress.tsx index 5906915..364ae23 100644 --- a/apps/frontend/src/components/status/AnalysisProgress.tsx +++ b/apps/frontend/src/components/status/AnalysisProgress.tsx @@ -22,7 +22,8 @@ const ORDER: AnalysisStage[] = [ const LABELS: Record = { IDLE: "Ready", - UPLOADING: "Uploading", + UPLOADING: "Getting Repository", + DOWNLOADING: "Getting Repository", EXTRACTING: "Extracting", READING_REPOSITORY: "Reading Repository", BUILDING_METADATA: "Building Metadata", @@ -38,7 +39,9 @@ const LABELS: Record = { export default function AnalysisProgress({ stage, }: Props) { - const current = ORDER.indexOf(stage); + const current = ORDER.indexOf( + stage === "DOWNLOADING" ? "UPLOADING" : stage, + ); return (
diff --git a/apps/frontend/src/components/upload/GitHubUrlInput.tsx b/apps/frontend/src/components/upload/GitHubUrlInput.tsx new file mode 100644 index 0000000..eb20497 --- /dev/null +++ b/apps/frontend/src/components/upload/GitHubUrlInput.tsx @@ -0,0 +1,64 @@ +import { FolderGit2 } from "lucide-react"; + +interface Props { + value: string; + onChange(value: string): void; + onSubmit(): void; +} + +/** + * Text field for a public GitHub repository URL. + */ +export default function GitHubUrlInput({ value, onChange, onSubmit }: Props) { + return ( +
+
+ +
+ +

+ Analyze a GitHub Repository +

+ +

+ Paste the link to a public repository. The latest commit on the + default branch is analyzed, or the branch in a /tree/ link. +

+ +
{ + event.preventDefault(); + onSubmit(); + }} + > + + + onChange(event.target.value)} + className="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900 outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200" + /> +
+ +
+

Accepted formats

+ +
    +
  • • https://github.com/owner/repository
  • +
  • • https://github.com/owner/repository/tree/branch
  • +
  • • owner/repository
  • +
  • • Private repositories: download them as a ZIP and upload instead.
  • +
+
+
+ ); +} diff --git a/apps/frontend/src/components/upload/SourceToggle.tsx b/apps/frontend/src/components/upload/SourceToggle.tsx new file mode 100644 index 0000000..bf48347 --- /dev/null +++ b/apps/frontend/src/components/upload/SourceToggle.tsx @@ -0,0 +1,48 @@ +import { FileArchive, FolderGit2 } from "lucide-react"; + +export type Source = "zip" | "github"; + +interface Props { + value: Source; + onChange(source: Source): void; +} + +const OPTIONS: Array<{ value: Source; label: string; icon: typeof FileArchive }> = [ + { value: "zip", label: "Upload ZIP", icon: FileArchive }, + { value: "github", label: "GitHub URL", icon: FolderGit2 }, +]; + +/** + * Chooses between uploading a ZIP and analyzing a GitHub URL. + */ +export default function SourceToggle({ value, onChange }: Props) { + return ( +
+ {OPTIONS.map(({ value: option, label, icon: Icon }) => { + const selected = option === value; + + return ( + + ); + })} +
+ ); +} diff --git a/apps/frontend/src/hooks/useAnalysis.ts b/apps/frontend/src/hooks/useAnalysis.ts index 7f47c39..bd2bc32 100644 --- a/apps/frontend/src/hooks/useAnalysis.ts +++ b/apps/frontend/src/hooks/useAnalysis.ts @@ -1,7 +1,11 @@ import { useEffect, useRef, useState } from "react"; import axios from "axios"; -import { startAnalysis, subscribeToJob } from "../services/api"; +import { + startAnalysis, + startGithubAnalysis, + subscribeToJob, +} from "../services/api"; import type { AnalyzeRepositoryResponse } from "../types/report"; import type { AnalysisProgress } from "../types/progress"; import type { @@ -68,7 +72,8 @@ export function useAnalysis() { return; } - if (body?.error === "UPLOAD_TOO_LARGE" || status === 413) { + // A bare 413 (no error code) comes from a proxy rejecting the upload. + if (body?.error === "UPLOAD_TOO_LARGE" || (status === 413 && !body?.error)) { setUploadTooLargeError({ ...UPLOAD_TOO_LARGE, message: body?.message ?? UPLOAD_TOO_LARGE.message, @@ -134,6 +139,13 @@ export function useAnalysis() { return; } + followJob(jobId); + } + + /** + * Follows a started job until it completes or fails. + */ + function followJob(jobId: string) { unsubscribeRef.current = subscribeToJob(jobId, { onProgress: setProgress, @@ -158,6 +170,44 @@ export function useAnalysis() { }); } + /** + * Analyzes a public GitHub repository by URL. + */ + async function analyzeGithub(url: string) { + unsubscribeRef.current?.(); + reset(); + + setLoading(true); + setProgress({ + stage: "DOWNLOADING", + message: "Checking the repository on GitHub...", + percentage: 2, + }); + + let jobId: string; + + try { + ({ jobId } = await startGithubAnalysis(url)); + } catch (requestError) { + if (axios.isAxiosError(requestError) && requestError.response) { + handleFailure( + requestError.response.data as ApiErrorBody | undefined, + requestError.response.status, + ); + return; + } + + handleFailure({ + success: false, + error: "NETWORK_ERROR", + message: "Could not reach the server. Please try again.", + }); + return; + } + + followJob(jobId); + } + return { loading, error, @@ -166,6 +216,7 @@ export function useAnalysis() { result, progress, analyze, + analyzeGithub, reset, }; } diff --git a/apps/frontend/src/pages/HomePage.tsx b/apps/frontend/src/pages/HomePage.tsx index d942341..54cfe90 100644 --- a/apps/frontend/src/pages/HomePage.tsx +++ b/apps/frontend/src/pages/HomePage.tsx @@ -5,6 +5,8 @@ import FloatingProgress from "../components/progress/FloatingProgress"; import Page from "../components/layout/Page"; import PageHeader from "../components/layout/PageHeader"; import UploadZone from "../components/upload/UploadZone"; +import GitHubUrlInput from "../components/upload/GitHubUrlInput"; +import SourceToggle, { type Source } from "../components/upload/SourceToggle"; import SelectedFile from "../components/upload/SelectedFile"; import AnalyzeButton from "../components/upload/AnalyzeButton"; import AnalysisProgress from "../components/status/AnalysisProgress"; @@ -16,14 +18,19 @@ import UploadTooLargeModal from "../components/errors/UploadTooLargeModal"; import { useAnalysis } from "../hooks/useAnalysis"; export default function HomePage() { + const [source, setSource] = useState("zip"); + const [file, setFile] = useState(null); + const [githubUrl, setGithubUrl] = useState(""); + const [showProgress, setShowProgress] = useState(true); const { analyze, + analyzeGithub, loading, error, result, @@ -35,6 +42,21 @@ export default function HomePage() { reset, } = useAnalysis(); + const canStart = + source === "zip" ? file !== null : githubUrl.trim().length > 0; + + function startAnalysis() { + if (!canStart || loading) return; + + setShowProgress(true); + + if (source === "zip") { + analyze(file!); + } else { + analyzeGithub(githubUrl.trim()); + } + } + return ( - + - {file && ( -
- + -
+ + {file && ( +
+ +
+ )} + + ) : ( + )}
{ - if (!file) return; - - setShowProgress(true); - - analyze(file); - }} + onClick={startAnalysis} />
diff --git a/apps/frontend/src/services/api.ts b/apps/frontend/src/services/api.ts index 0dcc480..ca4b173 100644 --- a/apps/frontend/src/services/api.ts +++ b/apps/frontend/src/services/api.ts @@ -38,6 +38,21 @@ export async function startAnalysis( return response.data; } +/** + * Starts a background analysis of a public GitHub repository. + * GitHub is checked before the job starts, so a bad URL or private + * repository fails here with a clear message. + */ +export async function startGithubAnalysis( + url: string, +): Promise<{ jobId: string }> { + const response = await api.post<{ jobId: string }>("/analyze/github", { + url, + }); + + return response.data; +} + export interface JobHandlers { onProgress: (progress: AnalysisProgress) => void; onCompleted: (result: AnalyzeRepositoryResponse) => void; diff --git a/apps/frontend/src/types/progress.ts b/apps/frontend/src/types/progress.ts index c9b53f5..6cf0a8e 100644 --- a/apps/frontend/src/types/progress.ts +++ b/apps/frontend/src/types/progress.ts @@ -1,6 +1,7 @@ export type AnalysisStage = | "IDLE" | "UPLOADING" + | "DOWNLOADING" | "EXTRACTING" | "READING_REPOSITORY" | "BUILDING_METADATA" diff --git a/apps/frontend/src/types/report.ts b/apps/frontend/src/types/report.ts index e5c95a3..b84750e 100644 --- a/apps/frontend/src/types/report.ts +++ b/apps/frontend/src/types/report.ts @@ -12,7 +12,19 @@ export type { import type { EngineeringReport } from "./report.schema.generated"; +/** + * Which repository a report is about. + */ +export interface RepositoryInfo { + /** "owner/repo" for GitHub, the ZIP's file name for uploads. */ + name: string; + url?: string; + ref?: string; + commitSha?: string; +} + export interface AnalyzeRepositoryResponse { report: EngineeringReport; markdown: string; + repository: RepositoryInfo; } From 0d75657a09b2124dfdcd9f9224c91f280643991d Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:50:12 +0530 Subject: [PATCH 5/5] Document GitHub URL analysis and GITHUB_TOKEN --- README.md | 9 +++++++-- apps/backend/.env.example | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4cbee26..f37cd81 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Each generated report includes: ## Intelligent Repository Analysis -- Upload repositories as ZIP archives +- Analyze a public GitHub repository by URL (any branch, tag or commit), or upload a ZIP archive - Automatic repository extraction - Repository root detection - Recursive repository traversal @@ -324,6 +324,11 @@ FRONTEND_URL=https://your-frontend.example # Optional: analyses allowed to run at once (extra uploads get HTTP 429) MAX_CONCURRENT_JOBS=2 +# Optional: GitHub token for analyzing by URL. Without it GitHub allows +# 60 API requests/hour from the server's IP; with it, 5,000. A fine-grained +# token with no extra permissions is enough (public repositories only). +# GITHUB_TOKEN=github_pat_... + # Optional: rate limits on starting analyses (0 = no limit) RATE_LIMIT_PER_HOUR=5 # per visitor (IP address) RATE_LIMIT_PER_DAY=100 # whole site @@ -347,6 +352,7 @@ SAVE_DEBUG_ARTIFACTS=false | Method | Path | Description | |---|---|---| | `POST` | `/api/analyze` | Upload a ZIP (`repository` form field). Returns `202 { jobId }`. | +| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo" }`. Public repositories only; checked on GitHub before the job starts. Returns `202 { jobId, repository }`. | | `GET` | `/api/jobs/:id/events` | Server-Sent Events: `progress`, then `completed` (report + markdown) or `failed` (error body). | | `GET` | `/api/jobs/:id` | Current job state as JSON. | | `GET` | `/api/health` | Health check. | @@ -381,7 +387,6 @@ Each analysis runs as its own job, so concurrent users never see each other's pr ## Version 1.1 -- GitHub Repository URL Analysis - Drag & Drop Uploads - Improved Language Detection - Repository Metrics Dashboard diff --git a/apps/backend/.env.example b/apps/backend/.env.example index e6eec6b..68ad4ea 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -5,6 +5,11 @@ GEMINI_MODEL=gemini-2.5-flash # Analyses allowed to run at once; extra uploads get HTTP 429. MAX_CONCURRENT_JOBS=2 +# Optional GitHub token for analyzing repositories by URL. +# Without it, GitHub allows 60 API requests/hour from the server's IP; with it, 5,000. +# A fine-grained token with no extra permissions is enough (public repos only). +# GITHUB_TOKEN= + # Rate limits on starting analyses (0 = no limit). # Per visitor (IP address) per hour, and for the whole site per day. RATE_LIMIT_PER_HOUR=5