From 2c654e40d05d945bf028981603e8eda90b756796 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 1/6] Connect to Postgres and create the reports table on startup --- apps/backend/package-lock.json | 168 ++++++++++++++++++++++++++++++ apps/backend/package.json | 3 + apps/backend/src/config/env.ts | 13 +++ apps/backend/src/db/database.ts | 101 ++++++++++++++++++ apps/backend/src/db/migrations.ts | 21 ++++ apps/backend/src/server.ts | 19 +++- 6 files changed, 324 insertions(+), 1 deletion(-) create mode 100644 apps/backend/src/db/database.ts create mode 100644 apps/backend/src/db/migrations.ts diff --git a/apps/backend/package-lock.json b/apps/backend/package-lock.json index 2ceb372..9aeb75d 100644 --- a/apps/backend/package-lock.json +++ b/apps/backend/package-lock.json @@ -13,13 +13,16 @@ "express": "^5.2.1", "express-rate-limit": "8.7.3", "multer": "^2.2.0", + "pg": "8.23.1", "typescript": "^6.0.3", "yauzl": "^2.10.0", "zod": "^4.4.3" }, "devDependencies": { + "@electric-sql/pglite": "0.5.15", "@types/cors": "^2.8.19", "@types/multer": "^2.1.0", + "@types/pg": "8.23.1", "@types/yauzl": "^2.10.3", "@types/yazl": "^3.3.1", "tsx": "^4.22.4", @@ -28,6 +31,13 @@ "yazl": "^3.3.1" } }, + "node_modules/@electric-sql/pglite": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.15.tgz", + "integrity": "sha512-ERZWgaRTxueGV4cvL1tfpAOzFCWTXoUtbCBqnf2FhHDVs/so9eAKaanvrwWF9Dntx7BYsmFQujVQ0/B4S8Mmiw==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@emnapi/core": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", @@ -1284,6 +1294,18 @@ "undici-types": "~8.3.0" } }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, "node_modules/@types/qs": { "version": "6.15.1", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", @@ -3767,6 +3789,95 @@ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", "license": "MIT" }, + "node_modules/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.14.1", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.1", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -3818,6 +3929,45 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -4218,6 +4368,15 @@ "node": ">=6.0.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -4688,6 +4847,15 @@ } } }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/yauzl": { "version": "2.10.0", "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", diff --git a/apps/backend/package.json b/apps/backend/package.json index 8017e16..81d0c22 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -11,8 +11,10 @@ "eval": "tsx scripts/eval.ts" }, "devDependencies": { + "@electric-sql/pglite": "0.5.15", "@types/cors": "^2.8.19", "@types/multer": "^2.1.0", + "@types/pg": "8.23.1", "@types/yauzl": "^2.10.3", "@types/yazl": "^3.3.1", "tsx": "^4.22.4", @@ -27,6 +29,7 @@ "express": "^5.2.1", "express-rate-limit": "8.7.3", "multer": "^2.2.0", + "pg": "8.23.1", "typescript": "^6.0.3", "yauzl": "^2.10.0", "zod": "^4.4.3" diff --git a/apps/backend/src/config/env.ts b/apps/backend/src/config/env.ts index e6abc4e..71e259a 100644 --- a/apps/backend/src/config/env.ts +++ b/apps/backend/src/config/env.ts @@ -49,6 +49,19 @@ const envSchema = z.object({ * How long a cached report is reused, in hours. */ REPORT_CACHE_TTL_HOURS: z.coerce.number().positive().default(168), + /** + * Postgres connection string (e.g. Neon). Enables saved reports with + * share links, and a report cache that survives restarts. Without it, + * reports are cached in memory only and sharing is unavailable. + */ + DATABASE_URL: z + .string() + .optional() + .transform((value) => value?.trim() || undefined), + /** + * Days a saved report (and its share link) is kept before deletion. + */ + REPORT_RETENTION_DAYS: z.coerce.number().positive().default(30), /** * 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/db/database.ts b/apps/backend/src/db/database.ts new file mode 100644 index 0000000..c427e03 --- /dev/null +++ b/apps/backend/src/db/database.ts @@ -0,0 +1,101 @@ +import pg from "pg"; + +import { env } from "../config/env.js"; +import { MIGRATIONS } from "./migrations.js"; + +/** + * The small part of a Postgres client the app needs. Implemented by a + * `pg` connection pool in production and by PGlite in tests. + */ +export interface Database { + query>( + text: string, + params?: unknown[], + ): Promise<{ rows: Row[]; rowCount: number }>; + close(): Promise; +} + +const CLEANUP_INTERVAL_MS = 60 * 60 * 1000; + +let database: Database | undefined; +let cleanupTimer: NodeJS.Timeout | undefined; + +export function createPostgresDatabase(connectionString: string): Database { + const pool = new pg.Pool({ + connectionString, + max: 5, + idleTimeoutMillis: 30_000, + connectionTimeoutMillis: 10_000, + }); + + // An idle client losing its connection (e.g. Neon scaling to zero) + // must not crash the server; the pool reconnects on the next query. + pool.on("error", (error) => { + console.error("Postgres pool error:", error.message); + }); + + return { + async query(text: string, params?: unknown[]) { + const result = await pool.query(text, params); + + return { rows: result.rows as Row[], rowCount: result.rowCount ?? 0 }; + }, + close: () => pool.end(), + }; +} + +/** + * Creates the tables (idempotent) and removes expired reports. + */ +export async function migrate(db: Database): Promise { + for (const statement of MIGRATIONS) { + await db.query(statement); + } +} + +export async function deleteExpiredReports(db: Database): Promise { + const result = await db.query("DELETE FROM reports WHERE expires_at <= now()"); + + return result.rowCount; +} + +/** + * Connects to DATABASE_URL (if set), creates the tables and starts the + * hourly cleanup of expired reports. Throws if the database is set but + * unreachable, so a wrong connection string is noticed at startup. + * + * Without DATABASE_URL the app still works: reports are cached in + * memory only and sharing is unavailable. + */ +export async function initDatabase(): Promise { + if (!env.DATABASE_URL) { + return undefined; + } + + const db = createPostgresDatabase(env.DATABASE_URL); + + await migrate(db); + await deleteExpiredReports(db); + + setDatabase(db); + + cleanupTimer = setInterval(() => { + deleteExpiredReports(db).catch((error: unknown) => { + console.error("Failed to delete expired reports:", error); + }); + }, CLEANUP_INTERVAL_MS); + cleanupTimer.unref(); + + return db; +} + +export function getDatabase(): Database | undefined { + return database; +} + +/** + * Sets the active database (used at startup, and by tests). + */ +export function setDatabase(db: Database | undefined): void { + database = db; +} diff --git a/apps/backend/src/db/migrations.ts b/apps/backend/src/db/migrations.ts new file mode 100644 index 0000000..d97d564 --- /dev/null +++ b/apps/backend/src/db/migrations.ts @@ -0,0 +1,21 @@ +/** + * Schema statements, run in order at startup. Each must be safe to run + * again (IF NOT EXISTS), because they run on every start. + */ +export const MIGRATIONS: string[] = [ + `CREATE TABLE IF NOT EXISTS reports ( + id UUID PRIMARY KEY, + -- Analysis version + input (GitHub commit or ZIP SHA-256) + cache_key TEXT NOT NULL UNIQUE, + report JSONB NOT NULL, + repository JSONB NOT NULL, + analyzed_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + -- Public link id, set only after the user clicks Share + share_id TEXT UNIQUE, + -- SHA-256 of the secret given to the browser that shared it + owner_token_hash TEXT, + shared_at TIMESTAMPTZ + )`, + `CREATE INDEX IF NOT EXISTS reports_expires_at_idx ON reports (expires_at)`, +]; diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index d776a48..a69a273 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -1,11 +1,28 @@ import app from "./app.js"; import { env } from "./config/env.js"; +import { initDatabase } from "./db/database.js"; const PORT = Number(process.env.PORT ?? 5000); +try { + const database = await initDatabase(); + + console.log( + database + ? "๐Ÿ—„๏ธ Database: connected (saved reports and share links enabled)" + : "๐Ÿ—„๏ธ Database: not configured (reports cached in memory, sharing disabled)", + ); +} catch (error) { + console.error( + "โŒ Could not connect to DATABASE_URL:", + error instanceof Error ? error.message : error, + ); + process.exit(1); +} + app.listen(PORT, () => { console.log("๐Ÿš€ RepoInsight-AI Backend"); console.log(`๐Ÿšช Listening on port ${PORT}`); console.log(`๐Ÿค– Gemini Model: ${env.GEMINI_MODEL}`); console.log(`๐ŸŒ Environment: ${process.env.NODE_ENV ?? "development"}`); -}); \ No newline at end of file +}); From fcdae6c39ca4710ea05ccdaafe71a2096c5ba59d Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 2/6] Save reports in Postgres and reuse them as the cache --- .../src/application/analysis-job.runner.ts | 7 +- .../src/cache/postgres-report-store.ts | 85 +++++++++++++++++++ apps/backend/src/cache/report-cache.ts | 65 ++++++++++++-- apps/backend/src/cache/report-store.ts | 18 ++-- apps/backend/src/jobs/job.types.ts | 5 ++ apps/backend/test/report-cache.test.ts | 6 +- 6 files changed, 166 insertions(+), 20 deletions(-) create mode 100644 apps/backend/src/cache/postgres-report-store.ts diff --git a/apps/backend/src/application/analysis-job.runner.ts b/apps/backend/src/application/analysis-job.runner.ts index 329ccb2..278dc47 100644 --- a/apps/backend/src/application/analysis-job.runner.ts +++ b/apps/backend/src/application/analysis-job.runner.ts @@ -10,7 +10,7 @@ import { downloadRepositoryZip } from "../github/github.client.js"; import { MAX_UPLOAD_SIZE } from "../constants/upload.js"; import { reportCache } from "../cache/report-cache.js"; -import type { AnalysisSource, JobContext } from "../jobs/job.types.js"; +import type { AnalysisSource, JobContext, JobResult } from "../jobs/job.types.js"; import type { RepositoryInfo } from "../types/repository-info.js"; const DOWNLOAD_DIRECTORY = "tmp/uploads"; @@ -93,7 +93,7 @@ export async function runAnalysisJob( // Deletes the ZIP and extracted files when done. const result = await analyzeUploadedRepository(zipPath, context, repository); - const jobResult = { + const jobResult: JobResult = { report: result.report, markdown: result.markdown, repository, @@ -102,7 +102,8 @@ export async function runAnalysisJob( }; if (options.cacheKey) { - await reportCache.save(options.cacheKey, jobResult); + // With a database, the saved report's id enables sharing. + jobResult.reportId = await reportCache.save(options.cacheKey, jobResult); } jobStore.complete(jobId, jobResult); diff --git a/apps/backend/src/cache/postgres-report-store.ts b/apps/backend/src/cache/postgres-report-store.ts new file mode 100644 index 0000000..f376d66 --- /dev/null +++ b/apps/backend/src/cache/postgres-report-store.ts @@ -0,0 +1,85 @@ +import { randomUUID } from "node:crypto"; + +import { buildMarkdown } from "../ai/report/markdown.service.js"; +import type { EngineeringReport } from "../ai/report/report.types.js"; +import type { Database } from "../db/database.js"; +import type { JobResult } from "../jobs/job.types.js"; +import type { RepositoryInfo } from "../types/repository-info.js"; +import type { ReportStore } from "./report-store.js"; + +interface ReportRow { + id: string; + report: EngineeringReport; + repository: RepositoryInfo; + analyzed_at: Date; +} + +/** + * Saved reports in Postgres. Each row is both a cache entry (looked up + * by cache key) and a report that can be shared by link. + * + * Only the report and repository are stored; the Markdown is rebuilt + * when read. Rows expire after REPORT_RETENTION_DAYS. + */ +export class PostgresReportStore implements ReportStore { + constructor( + private readonly db: Database, + private readonly retentionDays: number, + ) {} + + async get(key: string): Promise { + const { rows } = await this.db.query( + `SELECT id, report, repository, analyzed_at + FROM reports + WHERE cache_key = $1 AND expires_at > now()`, + [key], + ); + + const row = rows[0]; + + if (!row) { + return undefined; + } + + return { + report: row.report, + markdown: buildMarkdown(row.report, row.repository), + repository: row.repository, + analyzedAt: new Date(row.analyzed_at).toISOString(), + cached: false, + reportId: row.id, + }; + } + + /** + * Inserts the report, or replaces it if this input was analyzed before + * (a forced re-analysis). The id and any share link are kept, so an + * existing link shows the newest analysis of the same code. + */ + async set(key: string, result: JobResult): Promise { + const expiresAt = new Date( + Date.parse(result.analyzedAt) + this.retentionDays * 24 * 60 * 60 * 1000, + ); + + const { rows } = await this.db.query<{ id: string }>( + `INSERT INTO reports (id, cache_key, report, repository, analyzed_at, expires_at) + VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::timestamptz, $6::timestamptz) + ON CONFLICT (cache_key) DO UPDATE + SET report = EXCLUDED.report, + repository = EXCLUDED.repository, + analyzed_at = EXCLUDED.analyzed_at, + expires_at = EXCLUDED.expires_at + RETURNING id`, + [ + randomUUID(), + key, + JSON.stringify(result.report), + JSON.stringify(result.repository), + result.analyzedAt, + expiresAt.toISOString(), + ], + ); + + return rows[0].id; + } +} diff --git a/apps/backend/src/cache/report-cache.ts b/apps/backend/src/cache/report-cache.ts index 4843f63..80e14cf 100644 --- a/apps/backend/src/cache/report-cache.ts +++ b/apps/backend/src/cache/report-cache.ts @@ -7,6 +7,8 @@ import { jobStore } from "../jobs/job.store.js"; import type { JobResult } from "../jobs/job.types.js"; import { ANALYSIS_VERSION } from "./analysis-version.js"; import { MemoryReportStore, type ReportStore } from "./report-store.js"; +import { PostgresReportStore } from "./postgres-report-store.js"; +import { getDatabase, type Database } from "../db/database.js"; /** * Cache key for a GitHub commit. The repository name is included so a @@ -34,14 +36,37 @@ export async function uploadCacheKey(zipPath: string): Promise { export class ReportCache { private readonly inFlight = new Map(); - constructor(private readonly store: ReportStore) {} + /** + * @param store returns the store to use now (resolved per call, so a + * database connected after startup, or in tests, is picked up). + */ + constructor(private readonly store: () => ReportStore) {} + /** + * A stored report for this input, if any. A storage error is logged + * and treated as "not cached", so a database outage does not stop + * new analyses. + */ async lookup(key: string): Promise { - return this.store.get(key); + try { + return await this.store().get(key); + } catch (error) { + console.error("Report cache lookup failed:", error); + return undefined; + } } - async save(key: string, result: JobResult): Promise { - await this.store.set(key, result); + /** + * Stores a finished report. Returns its id when it can be shared. + * A storage error is logged and the report is simply not saved. + */ + async save(key: string, result: JobResult): Promise { + try { + return await this.store().set(key, result); + } catch (error) { + console.error("Saving report failed:", error); + return undefined; + } } /** @@ -70,9 +95,31 @@ export class ReportCache { } } -export const reportCache = new ReportCache( - new MemoryReportStore( - env.REPORT_CACHE_MAX_ENTRIES, - env.REPORT_CACHE_TTL_HOURS * 60 * 60 * 1000, - ), +const memoryStore = new MemoryReportStore( + env.REPORT_CACHE_MAX_ENTRIES, + env.REPORT_CACHE_TTL_HOURS * 60 * 60 * 1000, ); + +const postgresStores = new WeakMap(); + +/** + * Postgres when DATABASE_URL is configured, otherwise memory. + */ +function currentStore(): ReportStore { + const db = getDatabase(); + + if (!db) { + return memoryStore; + } + + let store = postgresStores.get(db); + + if (!store) { + store = new PostgresReportStore(db, env.REPORT_RETENTION_DAYS); + postgresStores.set(db, store); + } + + return store; +} + +export const reportCache = new ReportCache(currentStore); diff --git a/apps/backend/src/cache/report-store.ts b/apps/backend/src/cache/report-store.ts index 72cb88e..665f183 100644 --- a/apps/backend/src/cache/report-store.ts +++ b/apps/backend/src/cache/report-store.ts @@ -1,13 +1,16 @@ import type { JobResult } from "../jobs/job.types.js"; /** - * Where finished reports are kept for reuse. The in-memory store below - * is the default; a database-backed store can implement the same - * interface later (e.g. for saved, shareable reports). + * Where finished reports are kept for reuse: in memory by default, or in + * Postgres (PostgresReportStore) when DATABASE_URL is set. */ export interface ReportStore { get(key: string): Promise; - set(key: string, result: JobResult): Promise; + /** + * Saves (or replaces) the report for this key. Returns the saved + * report's id when it can be shared, otherwise undefined. + */ + set(key: string, result: JobResult): Promise; } interface Entry { @@ -48,9 +51,9 @@ export class MemoryReportStore implements ReportStore { return entry.result; } - async set(key: string, result: JobResult): Promise { + async set(key: string, result: JobResult): Promise { if (this.maxEntries <= 0) { - return; + return undefined; } this.entries.delete(key); @@ -60,6 +63,9 @@ export class MemoryReportStore implements ReportStore { const oldest = this.entries.keys().next().value as string; this.entries.delete(oldest); } + + // Reports in memory cannot be shared (they vanish on restart). + return undefined; } get size(): number { diff --git a/apps/backend/src/jobs/job.types.ts b/apps/backend/src/jobs/job.types.ts index 7bf7221..5d86d85 100644 --- a/apps/backend/src/jobs/job.types.ts +++ b/apps/backend/src/jobs/job.types.ts @@ -17,6 +17,11 @@ export interface JobResult { analyzedAt: string; /** True when this result was reused from the cache. */ cached: boolean; + /** + * Id of the saved report, present only when a database is configured. + * Needed to create a share link. + */ + reportId?: string; } /** diff --git a/apps/backend/test/report-cache.test.ts b/apps/backend/test/report-cache.test.ts index 9d8cd5a..2e820f2 100644 --- a/apps/backend/test/report-cache.test.ts +++ b/apps/backend/test/report-cache.test.ts @@ -52,8 +52,10 @@ describe("MemoryReportStore", () => { }); describe("ReportCache", () => { + const store = new MemoryReportStore(10, 60_000); + it("lets identical requests join a running job, until it finishes", () => { - const cache = new ReportCache(new MemoryReportStore(10, 60_000)); + const cache = new ReportCache(() => store); const job = jobStore.create(); cache.track("key", job.id); @@ -64,7 +66,7 @@ describe("ReportCache", () => { }); it("only releases the job it was tracking", () => { - const cache = new ReportCache(new MemoryReportStore(10, 60_000)); + const cache = new ReportCache(() => store); const newer = jobStore.create(); cache.track("key", newer.id); From 9668ba12fbc1381266c4fed991813a20de2b95a9 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 3/6] Add share links for saved reports --- apps/backend/src/app.ts | 3 + apps/backend/src/http/error-response.ts | 8 + apps/backend/src/http/rate-limit.ts | 20 +++ apps/backend/src/routes/reports.ts | 55 +++++++ apps/backend/src/sharing/share.errors.ts | 26 ++++ apps/backend/src/sharing/share.service.ts | 173 ++++++++++++++++++++++ 6 files changed, 285 insertions(+) create mode 100644 apps/backend/src/routes/reports.ts create mode 100644 apps/backend/src/sharing/share.errors.ts create mode 100644 apps/backend/src/sharing/share.service.ts diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index d412b96..dd64c71 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -4,6 +4,7 @@ import cors from "cors"; import analyzeRouter from "./routes/analyze.js"; import healthRouter from "./routes/health.js"; import jobsRouter from "./routes/jobs.js"; +import reportsRouter from "./routes/reports.js"; import { CorsError, toErrorResponse } from "./http/error-response.js"; import { env } from "./config/env.js"; @@ -36,6 +37,8 @@ app.use("/api", analyzeRouter); app.use("/api/jobs", jobsRouter); +app.use("/api", reportsRouter); + app.use("/api/health", healthRouter); app.use((_req, res) => { diff --git a/apps/backend/src/http/error-response.ts b/apps/backend/src/http/error-response.ts index 0c5366a..37cf8d5 100644 --- a/apps/backend/src/http/error-response.ts +++ b/apps/backend/src/http/error-response.ts @@ -5,6 +5,7 @@ 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"; +import { ShareError } from "../sharing/share.errors.js"; export class CorsError extends Error {} @@ -52,6 +53,13 @@ export function toErrorResponse(err: unknown): JobError { }; } + if (err instanceof ShareError) { + return { + status: err.status, + body: { success: false, error: err.code, message: err.message }, + }; + } + if (err instanceof GitHubError) { return { status: err.status, diff --git a/apps/backend/src/http/rate-limit.ts b/apps/backend/src/http/rate-limit.ts index 10f8b50..f11d0bc 100644 --- a/apps/backend/src/http/rate-limit.ts +++ b/apps/backend/src/http/rate-limit.ts @@ -90,3 +90,23 @@ export const analysisRateLimits: RequestHandler[] = [ }) : passThrough, ]; + +/** + * Light limit for the sharing endpoints (create, view, unshare). + * Share ids are 128-bit random values, so guessing is infeasible anyway; + * this keeps automated scraping and database load in check. + */ +export const shareRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 60, + keyGenerator: (req) => ipKeyGenerator(req.ip ?? "unknown"), + standardHeaders: "draft-8", + legacyHeaders: false, + handler: (_req, res) => { + res.status(429).json({ + success: false, + error: "RATE_LIMITED", + message: "Too many requests. Please wait a few minutes and try again.", + }); + }, +}); diff --git a/apps/backend/src/routes/reports.ts b/apps/backend/src/routes/reports.ts new file mode 100644 index 0000000..d71d186 --- /dev/null +++ b/apps/backend/src/routes/reports.ts @@ -0,0 +1,55 @@ +import { Router } from "express"; + +import { shareRateLimit } from "../http/rate-limit.js"; +import { + getSharedReport, + shareReport, + unshareReport, +} from "../sharing/share.service.js"; + +// The limit is attached per route: a router-level `use` would also run +// for every later /api route (such as /api/health). +const router = Router(); + +/** + * Creates a public link for a saved report (the reportId comes with a + * finished analysis when a database is configured). + * 200 { shareId, expiresAt, ownerToken? } + */ +router.post("/reports/:reportId/share", shareRateLimit, async (req, res) => { + const result = await shareReport(String(req.params.reportId)); + + res.json({ success: true, ...result }); +}); + +/** + * A shared report: { report, markdown, repository, analyzedAt, expiresAt } + */ +router.get("/shared/:shareId", shareRateLimit, async (req, res) => { + const shared = await getSharedReport(String(req.params.shareId)); + + res.set("Cache-Control", "private, max-age=60"); + res.set("X-Robots-Tag", "noindex"); + res.json({ success: true, ...shared }); +}); + +/** + * Removes a public link. Header: Authorization: Bearer + */ +router.delete("/shared/:shareId", shareRateLimit, async (req, res) => { + const token = req.get("authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1]; + + if (!token) { + return res.status(401).json({ + success: false, + error: "NOT_SHARE_OWNER", + message: "Only the browser that shared this report can unshare it.", + }); + } + + await unshareReport(String(req.params.shareId), token); + + return res.status(204).end(); +}); + +export default router; diff --git a/apps/backend/src/sharing/share.errors.ts b/apps/backend/src/sharing/share.errors.ts new file mode 100644 index 0000000..b23a8d1 --- /dev/null +++ b/apps/backend/src/sharing/share.errors.ts @@ -0,0 +1,26 @@ +export type ShareErrorCode = + | "SHARING_UNAVAILABLE" + | "REPORT_NOT_FOUND" + | "SHARED_REPORT_NOT_FOUND" + | "NOT_SHARE_OWNER"; + +const STATUS: Record = { + SHARING_UNAVAILABLE: 503, + REPORT_NOT_FOUND: 404, + SHARED_REPORT_NOT_FOUND: 404, + NOT_SHARE_OWNER: 403, +}; + +export class ShareError extends Error { + readonly code: ShareErrorCode; + + readonly status: number; + + constructor(code: ShareErrorCode, message: string) { + super(message); + + this.name = "ShareError"; + this.code = code; + this.status = STATUS[code]; + } +} diff --git a/apps/backend/src/sharing/share.service.ts b/apps/backend/src/sharing/share.service.ts new file mode 100644 index 0000000..19cecfe --- /dev/null +++ b/apps/backend/src/sharing/share.service.ts @@ -0,0 +1,173 @@ +import { createHash, randomBytes } from "node:crypto"; + +import { buildMarkdown } from "../ai/report/markdown.service.js"; +import type { EngineeringReport } from "../ai/report/report.types.js"; +import { getDatabase, type Database } from "../db/database.js"; +import type { RepositoryInfo } from "../types/repository-info.js"; +import { ShareError } from "./share.errors.js"; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** 16 random bytes as base64url: 22 characters, 128 bits. */ +const SHARE_ID = /^[A-Za-z0-9_-]{22}$/; + +export interface ShareResult { + shareId: string; + expiresAt: string; + /** + * Secret that allows removing the link. Returned only to the request + * that created the link; the database keeps only its SHA-256. + */ + ownerToken?: string; +} + +export interface SharedReport { + report: EngineeringReport; + markdown: string; + repository: RepositoryInfo; + analyzedAt: string; + expiresAt: string; +} + +function requireDatabase(): Database { + const db = getDatabase(); + + if (!db) { + throw new ShareError( + "SHARING_UNAVAILABLE", + "Sharing is not available on this server (no database configured).", + ); + } + + return db; +} + +function hashToken(token: string): string { + return createHash("sha256").update(token).digest("hex"); +} + +const notFound = () => + new ShareError( + "SHARED_REPORT_NOT_FOUND", + "This shared report does not exist, has expired, or was unshared.", + ); + +/** + * Creates a public link for a saved report. Sharing an already shared + * report returns the existing link without an owner token. + */ +export async function shareReport(reportId: string): Promise { + const db = requireDatabase(); + + const reportNotFound = new ShareError( + "REPORT_NOT_FOUND", + "This report is no longer available to share. Please analyze the repository again.", + ); + + if (!UUID.test(reportId)) { + throw reportNotFound; + } + + const shareId = randomBytes(16).toString("base64url"); + const ownerToken = randomBytes(32).toString("base64url"); + + const created = await db.query<{ share_id: string; expires_at: Date }>( + `UPDATE reports + SET share_id = $2, owner_token_hash = $3, shared_at = now() + WHERE id = $1 AND share_id IS NULL AND expires_at > now() + RETURNING share_id, expires_at`, + [reportId, shareId, hashToken(ownerToken)], + ); + + if (created.rows[0]) { + return { + shareId: created.rows[0].share_id, + expiresAt: new Date(created.rows[0].expires_at).toISOString(), + ownerToken, + }; + } + + const existing = await db.query<{ share_id: string | null; expires_at: Date }>( + `SELECT share_id, expires_at FROM reports WHERE id = $1 AND expires_at > now()`, + [reportId], + ); + + const row = existing.rows[0]; + + if (!row?.share_id) { + throw reportNotFound; + } + + return { + shareId: row.share_id, + expiresAt: new Date(row.expires_at).toISOString(), + }; +} + +export async function getSharedReport(shareId: string): Promise { + const db = requireDatabase(); + + if (!SHARE_ID.test(shareId)) { + throw notFound(); + } + + const { rows } = await db.query<{ + report: EngineeringReport; + repository: RepositoryInfo; + analyzed_at: Date; + expires_at: Date; + }>( + `SELECT report, repository, analyzed_at, expires_at + FROM reports + WHERE share_id = $1 AND expires_at > now()`, + [shareId], + ); + + const row = rows[0]; + + if (!row) { + throw notFound(); + } + + return { + report: row.report, + markdown: buildMarkdown(row.report, row.repository), + repository: row.repository, + analyzedAt: new Date(row.analyzed_at).toISOString(), + expiresAt: new Date(row.expires_at).toISOString(), + }; +} + +/** + * Removes a public link. Requires the owner token returned when the + * link was created. The report itself stays saved (for the cache). + */ +export async function unshareReport(shareId: string, ownerToken: string): Promise { + const db = requireDatabase(); + + if (!SHARE_ID.test(shareId)) { + throw notFound(); + } + + const removed = await db.query( + `UPDATE reports + SET share_id = NULL, owner_token_hash = NULL, shared_at = NULL + WHERE share_id = $1 AND owner_token_hash = $2`, + [shareId, hashToken(ownerToken)], + ); + + if (removed.rowCount > 0) { + return; + } + + const exists = await db.query(`SELECT 1 FROM reports WHERE share_id = $1`, [shareId]); + + if (exists.rows.length > 0) { + throw new ShareError( + "NOT_SHARE_OWNER", + "Only the browser that shared this report can unshare it.", + ); + } + + throw notFound(); +} From 09b9dc8e032f1ea19cc6fab3273dfd0f37394eb0 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 4/6] Test saved reports and sharing with PGlite --- apps/backend/test/helpers/database.ts | 28 ++++ apps/backend/test/saved-reports-http.test.ts | 129 ++++++++++++++++ apps/backend/test/saved-reports.test.ts | 152 +++++++++++++++++++ apps/backend/vitest.config.ts | 3 + 4 files changed, 312 insertions(+) create mode 100644 apps/backend/test/helpers/database.ts create mode 100644 apps/backend/test/saved-reports-http.test.ts create mode 100644 apps/backend/test/saved-reports.test.ts diff --git a/apps/backend/test/helpers/database.ts b/apps/backend/test/helpers/database.ts new file mode 100644 index 0000000..2cb6ac0 --- /dev/null +++ b/apps/backend/test/helpers/database.ts @@ -0,0 +1,28 @@ +import { PGlite } from "@electric-sql/pglite"; + +import { migrate, type Database } from "../../src/db/database.js"; + +/** + * A real Postgres (PGlite, in memory) behind the app's Database + * interface, with the schema applied. + */ +export async function createTestDatabase(): Promise { + const pglite = new PGlite(); + + const db = { + pglite, + async query(text: string, params?: unknown[]) { + const result = await pglite.query(text, params); + + return { + rows: result.rows, + rowCount: result.affectedRows ?? result.rows.length, + }; + }, + close: () => pglite.close(), + }; + + await migrate(db); + + return db; +} diff --git a/apps/backend/test/saved-reports-http.test.ts b/apps/backend/test/saved-reports-http.test.ts new file mode 100644 index 0000000..485c57d --- /dev/null +++ b/apps/backend/test/saved-reports-http.test.ts @@ -0,0 +1,129 @@ +import fs from "node:fs/promises"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +import { createZip } from "./helpers/zip.js"; +import { createTestDatabase } from "./helpers/database.js"; + +process.env.RATE_LIMIT_PER_HOUR = "0"; +process.env.RATE_LIMIT_PER_DAY = "0"; +process.env.MAX_CONCURRENT_JOBS = "100"; + +vi.mock("../src/ai/gemini/gemini.client.js", () => ({ + generateContent: vi.fn(), +})); + +const { default: app } = await import("../src/app.js"); +const { generateContent } = await import("../src/ai/gemini/gemini.client.js"); +const { jobStore } = await import("../src/jobs/job.store.js"); +const { setDatabase } = await import("../src/db/database.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: [], +}; + +let server: Server; +let baseUrl: string; +let db: Awaited>; + +beforeAll(async () => { + vi.mocked(generateContent).mockResolvedValue({ text: JSON.stringify(report) }); + + db = await createTestDatabase(); + setDatabase(db); + + server = app.listen(0); + await new Promise((resolve) => server.once("listening", resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + server.close(); + setDatabase(undefined); + await db.close(); +}); + +async function analyzeZip(content: string) { + const bytes = new Uint8Array( + await fs.readFile(await createZip([{ name: "repo/index.ts", content }])), + ); + const form = new FormData(); + form.append("repository", new Blob([bytes]), "demo.zip"); + + const response = await fetch(`${baseUrl}/api/analyze`, { method: "POST", body: form }); + const { jobId } = (await response.json()) as { jobId: string }; + + await vi.waitFor(() => { + expect(jobStore.get(jobId)?.status).not.toBe("running"); + }); + + return jobStore.get(jobId)!; +} + +describe("saved reports over HTTP", () => { + it("shares a finished report, serves it by link and unshares it", async () => { + const job = await analyzeZip("export const shared = 1;"); + const reportId = job.result?.reportId; + + expect(reportId).toMatch(/^[0-9a-f-]{36}$/); + + const shareResponse = await fetch(`${baseUrl}/api/reports/${reportId}/share`, { + method: "POST", + }); + const share = (await shareResponse.json()) as { shareId: string; ownerToken: string }; + + expect(shareResponse.status).toBe(200); + + const viewResponse = await fetch(`${baseUrl}/api/shared/${share.shareId}`); + const view = (await viewResponse.json()) as { repository: { name: string }; markdown: string }; + + expect(viewResponse.status).toBe(200); + expect(viewResponse.headers.get("x-robots-tag")).toBe("noindex"); + expect(view.repository.name).toBe("demo"); + expect(view.markdown).toContain("# AI Project Review"); + + const forbidden = await fetch(`${baseUrl}/api/shared/${share.shareId}`, { + method: "DELETE", + headers: { Authorization: "Bearer not-the-token" }, + }); + expect(forbidden.status).toBe(403); + + const removed = await fetch(`${baseUrl}/api/shared/${share.shareId}`, { + method: "DELETE", + headers: { Authorization: `Bearer ${share.ownerToken}` }, + }); + expect(removed.status).toBe(204); + + const gone = await fetch(`${baseUrl}/api/shared/${share.shareId}`); + expect(gone.status).toBe(404); + }); + + it("serves a repeat analysis from the database with the same report id", async () => { + const callsBefore = vi.mocked(generateContent).mock.calls.length; + + const first = await analyzeZip("export const again = 1;"); + const second = await analyzeZip("export const again = 1;"); + + expect(second.result?.cached).toBe(true); + expect(second.result?.reportId).toBe(first.result?.reportId); + // Only the first of the two identical uploads called Gemini. + expect(vi.mocked(generateContent).mock.calls.length - callsBefore).toBe(1); + }); + + it("does not rate limit unrelated routes such as the health check", async () => { + for (let i = 0; i < 70; i++) { + const health = await fetch(`${baseUrl}/api/health`); + expect(health.status).toBe(200); + } + }); +}); diff --git a/apps/backend/test/saved-reports.test.ts b/apps/backend/test/saved-reports.test.ts new file mode 100644 index 0000000..e2df3dd --- /dev/null +++ b/apps/backend/test/saved-reports.test.ts @@ -0,0 +1,152 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { createTestDatabase } from "./helpers/database.js"; +import { PostgresReportStore } from "../src/cache/postgres-report-store.js"; +import { deleteExpiredReports, setDatabase, type Database } from "../src/db/database.js"; +import { + getSharedReport, + shareReport, + unshareReport, +} from "../src/sharing/share.service.js"; +import { ShareError } from "../src/sharing/share.errors.js"; +import type { JobResult } from "../src/jobs/job.types.js"; + +const report = { + summary: { purpose: "Demo app", 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: 6, positives: [], negatives: [], recommendations: [] }, + strengths: [], + weaknesses: [], + improvements: [], + resumeFeedback: { score: 7, summary: "s", strengths: [], improvements: [], bestResumeBullets: [] }, + interviewQuestions: [], +}; + +function result(overrides: Partial = {}): JobResult { + return { + report, + markdown: "ignored: rebuilt when read", + repository: { name: "Owner/Repo", url: "https://github.com/Owner/Repo", commitSha: "f".repeat(40) }, + analyzedAt: new Date().toISOString(), + cached: false, + ...overrides, + }; +} + +async function shareErrorCode(promise: Promise): Promise { + const error = await promise.catch((e: unknown) => e); + + expect(error).toBeInstanceOf(ShareError); + + return (error as ShareError).code; +} + +let db: Database; +let store: PostgresReportStore; + +beforeEach(async () => { + db = await createTestDatabase(); + store = new PostgresReportStore(db, 30); + setDatabase(db); +}); + +afterEach(async () => { + setDatabase(undefined); + await db.close(); +}); + +describe("PostgresReportStore", () => { + it("saves a report and finds it by cache key, rebuilding the Markdown", async () => { + const id = await store.set("key-1", result()); + const found = await store.get("key-1"); + + expect(found?.reportId).toBe(id); + expect(found?.report).toEqual(report); + expect(found?.markdown).toContain("**Repository:** [Owner/Repo](https://github.com/Owner/Repo)"); + expect(found?.markdown).toContain("Demo app"); + expect(await store.get("other-key")).toBeUndefined(); + }); + + it("replaces the report on re-analysis but keeps its id", async () => { + const first = await store.set("key-1", result({ analyzedAt: "2026-11-01T00:00:00.000Z" })); + const second = await store.set("key-1", result()); + + expect(second).toBe(first); + expect((await store.get("key-1"))?.analyzedAt).not.toBe("2026-11-01T00:00:00.000Z"); + }); + + it("ignores and deletes expired reports", async () => { + await store.set("old", result({ analyzedAt: "2020-01-01T00:00:00.000Z" })); + await store.set("new", result()); + + expect(await store.get("old")).toBeUndefined(); + expect(await deleteExpiredReports(db)).toBe(1); + expect(await store.get("new")).toBeDefined(); + }); +}); + +describe("sharing", () => { + it("creates a link once and returns the same link afterwards", async () => { + const reportId = await store.set("key-1", result()); + + const first = await shareReport(reportId); + expect(first.shareId).toMatch(/^[A-Za-z0-9_-]{22}$/); + expect(first.ownerToken).toBeTruthy(); + + const again = await shareReport(reportId); + expect(again.shareId).toBe(first.shareId); + expect(again.ownerToken).toBeUndefined(); + }); + + it("serves the shared report until the owner unshares it", async () => { + const reportId = await store.set("key-1", result()); + const { shareId, ownerToken } = await shareReport(reportId); + + const shared = await getSharedReport(shareId); + expect(shared.report).toEqual(report); + expect(shared.repository.name).toBe("Owner/Repo"); + expect(Date.parse(shared.expiresAt)).toBeGreaterThan(Date.now()); + + expect(await shareErrorCode(unshareReport(shareId, "wrong-token"))).toBe("NOT_SHARE_OWNER"); + + await unshareReport(shareId, ownerToken!); + + expect(await shareErrorCode(getSharedReport(shareId))).toBe("SHARED_REPORT_NOT_FOUND"); + + // The report itself stays saved for the cache. + expect(await store.get("key-1")).toBeDefined(); + }); + + it("stores only a hash of the owner token", async () => { + const reportId = await store.set("key-1", result()); + const { ownerToken } = await shareReport(reportId); + + const { rows } = await db.query<{ owner_token_hash: string }>( + "SELECT owner_token_hash FROM reports WHERE id = $1", + [reportId], + ); + + expect(rows[0].owner_token_hash).toMatch(/^[0-9a-f]{64}$/); + expect(rows[0].owner_token_hash).not.toContain(ownerToken!); + }); + + it("does not share or serve expired reports", async () => { + const reportId = await store.set("old", result({ analyzedAt: "2020-01-01T00:00:00.000Z" })); + + expect(await shareErrorCode(shareReport(reportId))).toBe("REPORT_NOT_FOUND"); + }); + + it("rejects malformed ids without querying", async () => { + expect(await shareErrorCode(shareReport("not-a-uuid"))).toBe("REPORT_NOT_FOUND"); + expect(await shareErrorCode(getSharedReport("short"))).toBe("SHARED_REPORT_NOT_FOUND"); + expect(await shareErrorCode(getSharedReport("x".repeat(22)))).toBe("SHARED_REPORT_NOT_FOUND"); + }); + + it("is unavailable without a database", async () => { + setDatabase(undefined); + + expect(await shareErrorCode(getSharedReport("x".repeat(22)))).toBe("SHARING_UNAVAILABLE"); + }); +}); diff --git a/apps/backend/vitest.config.ts b/apps/backend/vitest.config.ts index 497c740..31892ae 100644 --- a/apps/backend/vitest.config.ts +++ b/apps/backend/vitest.config.ts @@ -17,6 +17,9 @@ export default defineConfig({ // env.ts requires a key at import time; tests never call Gemini. GEMINI_API_KEY: "test-key", SAVE_DEBUG_ARTIFACTS: "false", + // Never use a real database from .env in tests (PGlite is used instead). + DATABASE_URL: "", + GITHUB_TOKEN: "", TMPDIR: testTmpDir, }, }, From ff06b9a1b9c703944af63cbdc1c20ae0f1800b3d Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 5/6] Add Share button and shared report page --- apps/frontend/src/App.tsx | 12 +- .../src/components/report/ReportViewer.tsx | 31 +++- .../src/components/report/ShareControls.tsx | 160 ++++++++++++++++++ apps/frontend/src/pages/HomePage.tsx | 6 + apps/frontend/src/pages/SharedReportPage.tsx | 110 ++++++++++++ apps/frontend/src/services/api.ts | 36 +++- apps/frontend/src/sharing/shareLinks.ts | 46 +++++ apps/frontend/src/types/report.ts | 17 ++ apps/frontend/vercel.json | 10 ++ 9 files changed, 416 insertions(+), 12 deletions(-) create mode 100644 apps/frontend/src/components/report/ShareControls.tsx create mode 100644 apps/frontend/src/pages/SharedReportPage.tsx create mode 100644 apps/frontend/src/sharing/shareLinks.ts create mode 100644 apps/frontend/vercel.json diff --git a/apps/frontend/src/App.tsx b/apps/frontend/src/App.tsx index 7169259..959e458 100644 --- a/apps/frontend/src/App.tsx +++ b/apps/frontend/src/App.tsx @@ -1,5 +1,13 @@ import HomePage from "./pages/HomePage"; +import SharedReportPage from "./pages/SharedReportPage"; +import { currentShareId } from "./sharing/shareLinks"; +/** + * Two pages: the analyzer, and shared reports at /r/. + * (Vercel serves index.html for /r/* via vercel.json.) + */ export default function App() { - return ; -} \ No newline at end of file + const shareId = currentShareId(); + + return shareId ? : ; +} diff --git a/apps/frontend/src/components/report/ReportViewer.tsx b/apps/frontend/src/components/report/ReportViewer.tsx index a5e04cc..297480a 100644 --- a/apps/frontend/src/components/report/ReportViewer.tsx +++ b/apps/frontend/src/components/report/ReportViewer.tsx @@ -1,3 +1,5 @@ +import type { ReactNode } from "react"; + import type { AnalyzeRepositoryResponse } from "../../types/report"; import ArchitectureCard from "./ArchitectureCard"; @@ -15,22 +17,29 @@ import TechnologyStackCard from "./TechnologyStackCard"; import WeaknessesCard from "./WeaknessesCard"; interface Props { - result: AnalyzeRepositoryResponse; - loading: boolean; - onReanalyze(): void; + result: Pick< + AnalyzeRepositoryResponse, + "report" | "markdown" | "repository" | "analyzedAt" + > & { cached?: boolean }; + loading?: boolean; + /** Offered on cached results; omitted on shared-report pages. */ + onReanalyze?(): void; + /** Extra header actions, e.g. the Share controls. */ + actions?: ReactNode; } export default function ReportViewer({ result, - loading, + loading = false, onReanalyze, + actions, }: Props) { const { report, markdown, repository } = result; return (
- {result.cached && ( + {result.cached && onReanalyze && ( )} -
+
@@ -75,9 +84,13 @@ export default function ReportViewer({
- +
+ + + {actions} +
diff --git a/apps/frontend/src/components/report/ShareControls.tsx b/apps/frontend/src/components/report/ShareControls.tsx new file mode 100644 index 0000000..13a73a9 --- /dev/null +++ b/apps/frontend/src/components/report/ShareControls.tsx @@ -0,0 +1,160 @@ +import { useState } from "react"; +import axios from "axios"; +import { Check, Copy, Link2, LoaderCircle, Link2Off } from "lucide-react"; + +import { shareReport, unshareReport } from "../../services/api"; +import { + forgetOwnerToken, + getOwnerToken, + saveOwnerToken, + shareUrl, +} from "../../sharing/shareLinks"; + +interface Props { + /** Saved report that can be shared (results page). */ + reportId?: string; + /** Already shared report (shared-report page). */ + shareId?: string; + /** Called after this browser removed the link. */ + onUnshared?(): void; +} + +function errorMessage(error: unknown, fallback: string): string { + if (axios.isAxiosError(error)) { + const message = (error.response?.data as { message?: unknown } | undefined)?.message; + + if (typeof message === "string") return message; + } + + return fallback; +} + +/** + * Share button, then the link with Copy and (for the browser that + * shared it) Stop sharing. + */ +export default function ShareControls({ reportId, shareId: initialShareId, onUnshared }: Props) { + const [shareId, setShareId] = useState(initialShareId); + const [busy, setBusy] = useState(false); + const [copied, setCopied] = useState(false); + const [error, setError] = useState(""); + + const canUnshare = shareId ? getOwnerToken(shareId) !== undefined : false; + + async function share() { + if (!reportId) return; + + setBusy(true); + setError(""); + + try { + const result = await shareReport(reportId); + + if (result.ownerToken) { + saveOwnerToken(result.shareId, result.ownerToken); + } + + setShareId(result.shareId); + } catch (shareError) { + setError(errorMessage(shareError, "Could not create a share link. Please try again.")); + } finally { + setBusy(false); + } + } + + async function copy() { + if (!shareId) return; + + try { + await navigator.clipboard.writeText(shareUrl(shareId)); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch { + setError("Copy failed. Select the link and copy it manually."); + } + } + + async function unshare() { + const token = shareId ? getOwnerToken(shareId) : undefined; + + if (!shareId || !token) return; + + setBusy(true); + setError(""); + + try { + await unshareReport(shareId, token); + forgetOwnerToken(shareId); + setShareId(undefined); + onUnshared?.(); + } catch (unshareError) { + setError(errorMessage(unshareError, "Could not remove the link. Please try again.")); + } finally { + setBusy(false); + } + } + + if (!shareId && !reportId) { + return null; + } + + return ( +
+ {!shareId ? ( + + ) : ( +
+
+ event.target.select()} + className="min-w-0 flex-1 rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-700" + /> + +
+ +

+ Anyone with this link can view the report, including code snippets. + {canUnshare && ( + <> + {" "} + + + )} +

+
+ )} + + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/apps/frontend/src/pages/HomePage.tsx b/apps/frontend/src/pages/HomePage.tsx index 9f96015..565d19a 100644 --- a/apps/frontend/src/pages/HomePage.tsx +++ b/apps/frontend/src/pages/HomePage.tsx @@ -11,6 +11,7 @@ import SelectedFile from "../components/upload/SelectedFile"; import AnalyzeButton from "../components/upload/AnalyzeButton"; import AnalysisProgress from "../components/status/AnalysisProgress"; import ReportViewer from "../components/report/ReportViewer"; +import ShareControls from "../components/report/ShareControls"; import ProgressModal from "../components/progress/ProgressModal"; import RepositoryTooLargeModal from "../components/errors/RepositoryTooLargeModal"; import UploadTooLargeModal from "../components/errors/UploadTooLargeModal"; @@ -116,6 +117,11 @@ export default function HomePage() { + ) + } onReanalyze={() => { setShowProgress(true); reanalyze(); diff --git a/apps/frontend/src/pages/SharedReportPage.tsx b/apps/frontend/src/pages/SharedReportPage.tsx new file mode 100644 index 0000000..a8df2a9 --- /dev/null +++ b/apps/frontend/src/pages/SharedReportPage.tsx @@ -0,0 +1,110 @@ +import { useEffect, useState } from "react"; +import axios from "axios"; +import { CalendarClock, LoaderCircle, SearchX } from "lucide-react"; + +import Page from "../components/layout/Page"; +import ReportViewer from "../components/report/ReportViewer"; +import ShareControls from "../components/report/ShareControls"; +import { getSharedReport } from "../services/api"; +import type { SharedReportResponse } from "../types/report"; + +interface Props { + shareId: string; +} + +type State = + | { status: "loading" } + | { status: "loaded"; report: SharedReportResponse } + | { status: "missing"; message: string } + | { status: "unshared" }; + +function formatDate(iso: string): string { + return new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" }); +} + +/** + * A report opened from a share link (/r/). Read-only. + */ +export default function SharedReportPage({ shareId }: Props) { + const [state, setState] = useState({ status: "loading" }); + + useEffect(() => { + let active = true; + + getSharedReport(shareId) + .then((report) => { + if (active) setState({ status: "loaded", report }); + }) + .catch((error: unknown) => { + if (!active) return; + + const message = + axios.isAxiosError(error) && typeof error.response?.data?.message === "string" + ? error.response.data.message + : "This report could not be loaded. Please try again later."; + + setState({ status: "missing", message }); + }); + + return () => { + active = false; + }; + }, [shareId]); + + return ( + + + + {state.status === "loading" && ( +
+ + Loading shared report... +
+ )} + + {(state.status === "missing" || state.status === "unshared") && ( +
+ +

+ {state.status === "unshared" ? "Link removed" : "Report not available"} +

+

+ {state.status === "unshared" + ? "This report is no longer shared. The link has stopped working for everyone." + : state.message} +

+
+ )} + + {state.status === "loaded" && ( + <> +

+ + Shared report ยท analyzed {formatDate(state.report.analyzedAt)} ยท link + expires {formatDate(state.report.expiresAt)} +

+ + setState({ status: "unshared" })} + /> + } + /> + + )} +
+ ); +} diff --git a/apps/frontend/src/services/api.ts b/apps/frontend/src/services/api.ts index 774068d..6046fd9 100644 --- a/apps/frontend/src/services/api.ts +++ b/apps/frontend/src/services/api.ts @@ -1,6 +1,10 @@ import axios from "axios"; -import type { AnalyzeRepositoryResponse } from "../types/report"; +import type { + AnalyzeRepositoryResponse, + SharedReportResponse, + ShareResponse, +} from "../types/report"; import type { AnalysisProgress } from "../types/progress"; import type { ApiErrorBody } from "../types/errors"; @@ -115,3 +119,33 @@ export function subscribeToJob( return finish; } + +/** + * Creates (or returns the existing) public link for a saved report. + */ +export async function shareReport(reportId: string): Promise { + const response = await api.post( + `/reports/${encodeURIComponent(reportId)}/share`, + ); + + return response.data; +} + +export async function getSharedReport( + shareId: string, +): Promise { + const response = await api.get( + `/shared/${encodeURIComponent(shareId)}`, + ); + + return response.data; +} + +export async function unshareReport( + shareId: string, + ownerToken: string, +): Promise { + await api.delete(`/shared/${encodeURIComponent(shareId)}`, { + headers: { Authorization: `Bearer ${ownerToken}` }, + }); +} diff --git a/apps/frontend/src/sharing/shareLinks.ts b/apps/frontend/src/sharing/shareLinks.ts new file mode 100644 index 0000000..54de2a1 --- /dev/null +++ b/apps/frontend/src/sharing/shareLinks.ts @@ -0,0 +1,46 @@ +/** + * Share links and the owner tokens that allow unsharing them. + * + * Tokens live in this browser's localStorage, so only the browser that + * shared a report can unshare it. Storage can be unavailable (private + * mode, blocked site data): then unsharing is simply not offered. + */ + +const PREFIX = "repoinsight:share-owner:"; + +export const SHARE_PATH = /^\/r\/([A-Za-z0-9_-]{22})\/?$/; + +export function shareUrl(shareId: string): string { + return `${window.location.origin}/r/${shareId}`; +} + +/** + * The share id in the current URL (/r/), if this is a shared-report page. + */ +export function currentShareId(): string | undefined { + return window.location.pathname.match(SHARE_PATH)?.[1]; +} + +export function saveOwnerToken(shareId: string, token: string): void { + try { + window.localStorage.setItem(PREFIX + shareId, token); + } catch { + // Storage unavailable: the link works, unsharing from here does not. + } +} + +export function getOwnerToken(shareId: string): string | undefined { + try { + return window.localStorage.getItem(PREFIX + shareId) ?? undefined; + } catch { + return undefined; + } +} + +export function forgetOwnerToken(shareId: string): void { + try { + window.localStorage.removeItem(PREFIX + shareId); + } catch { + // Nothing to clean up. + } +} diff --git a/apps/frontend/src/types/report.ts b/apps/frontend/src/types/report.ts index 746c35c..3166410 100644 --- a/apps/frontend/src/types/report.ts +++ b/apps/frontend/src/types/report.ts @@ -31,4 +31,21 @@ export interface AnalyzeRepositoryResponse { analyzedAt: string; /** True when the same input was analyzed before and the report reused. */ cached: boolean; + /** Present when the server saves reports; needed to share one. */ + reportId?: string; +} + +export interface ShareResponse { + shareId: string; + expiresAt: string; + /** Only for the request that created the link; allows unsharing. */ + ownerToken?: string; +} + +export interface SharedReportResponse { + report: EngineeringReport; + markdown: string; + repository: RepositoryInfo; + analyzedAt: string; + expiresAt: string; } diff --git a/apps/frontend/vercel.json b/apps/frontend/vercel.json new file mode 100644 index 0000000..ad24cd4 --- /dev/null +++ b/apps/frontend/vercel.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "rewrites": [{ "source": "/r/:shareId", "destination": "/index.html" }], + "headers": [ + { + "source": "/r/(.*)", + "headers": [{ "key": "X-Robots-Tag", "value": "noindex" }] + } + ] +} From 12ad2501b3163ff223c1af2cdbd3a62029343eed Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:25:19 +0530 Subject: [PATCH 6/6] Document saved and shared reports --- README.md | 17 ++++++++++++++++- apps/backend/.env.example | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d3a86e7..ed72301 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,11 @@ MAX_CONCURRENT_JOBS=2 # token with no extra permissions is enough (public repositories only). # GITHUB_TOKEN=github_pat_... +# Optional: Postgres (e.g. Neon) for saved reports, share links and a +# cache that survives restarts. Tables are created on startup. +# DATABASE_URL=postgresql://user:password@host/db?sslmode=require +REPORT_RETENTION_DAYS=30 + # Optional: reuse reports when the same GitHub commit or the same ZIP is # analyzed again (in memory; cleared on restart). 0 entries = no caching. REPORT_CACHE_MAX_ENTRIES=50 @@ -360,8 +365,19 @@ SAVE_DEBUG_ARTIFACTS=false | `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo", "force"?: true }`. Public repositories only; checked on GitHub before the job starts. | | `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. | +| `POST` | `/api/reports/:reportId/share` | Create a public link for a saved report. Returns `{ shareId, expiresAt, ownerToken }` (the token only the first time). | +| `GET` | `/api/shared/:shareId` | A shared report. | +| `DELETE` | `/api/shared/:shareId` | Remove the link. Header `Authorization: Bearer `. | | `GET` | `/api/health` | Health check. | +## Saved and Shared Reports + +With `DATABASE_URL` set, every finished report is saved in Postgres for `REPORT_RETENTION_DAYS` (default 30) and also serves as the report cache, so it survives restarts. + +A report becomes public only when the user clicks **Share**: it then gets a link like `/r/` (128-bit random id, not indexed by search engines). The browser that shared it keeps a secret token (only its SHA-256 is stored) and can **Stop sharing** at any time. Expired reports and links are deleted automatically. + +Without a database, reports are cached in memory only and sharing is unavailable. + Both analyze endpoints return a `jobId` to follow: - `202` a new analysis started @@ -414,7 +430,6 @@ Each analysis runs as its own job, so concurrent users never see each other's pr ## Version 2.0 - User Authentication -- Saved Reports - Analysis History - GitHub OAuth - Repository Comparison diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 47149ab..06ab076 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -10,6 +10,11 @@ MAX_CONCURRENT_JOBS=2 # A fine-grained token with no extra permissions is enough (public repos only). # GITHUB_TOKEN= +# Postgres (e.g. Neon) for saved reports, share links and a restart-proof +# cache. Tables are created on startup. Leave unset to keep everything in memory. +# DATABASE_URL=postgresql://user:password@host/db?sslmode=require +REPORT_RETENTION_DAYS=30 + # Reuse reports when the same GitHub commit or ZIP is analyzed again # (in memory; cleared on restart). 0 entries = no caching. REPORT_CACHE_MAX_ENTRIES=50