How kanif-kumbhar/pdf-analyzer works
1. Overall shape
- This is a single Next.js monolith: UI, server route handlers, security checks, caching, and AI orchestration all live in one deployable app.
- The main architectural boundary is browser vs. server. The client submits a URL or PDF file, but all fetching, validation, caching, and Gemini access happen server-side.
2. Presentation layer
- The app shell is in app/layout.tsx, app/page.tsx, and app/globals.css.
- The analyzer UI is split into reusable components under components/analyzer, including the URL form, drag-and-drop upload zone, loading skeleton, error state, and structured result cards/lists.
- The UI is designed to consume a single structured analysis result object and render metadata, topics, takeaways, and key points.
3. API surface
- The primary entrypoint is POST /api/analyze for analyzing a PDF from a public URL.
- POST /api/analyze/upload handles direct file uploads.
- GET/POST /api/analyze/cached appears to support cache retrieval or cache-backed analysis lookup.
- GET /api/history exposes prior analyses, and GET /api/limit likely exposes rate-limit status for the client.
4. Request orchestration pipeline
- Requests first pass through schema validation (lib/validation/analyze-request.ts).
- URLs are normalized/transformed (lib/url/transform-url.ts), then validated for safety.
- The server either returns a cached result or fetches and analyzes the PDF.
- The pipeline is intentionally synchronous: one request can perform fetch, validation, AI analysis, persistence, and response assembly end-to-end.
5. Document ingestion and PDF handling
- URL-based ingestion uses lib/pdf/fetch-pdf.ts to stream the remote document.
- Upload-based ingestion uses lib/pdf/validate-upload.ts to enforce file safety and size limits.
- lib/pdf/metadata.ts and lib/analysis/reading-time.ts compute deterministic document metadata such as page count and estimated reading time.
- A PDF signature check and incremental byte-size enforcement are part of the trust boundary before any AI work begins.
6. Security boundary
- SSRF protection is a core subsystem: lib/security/validate-url.ts and lib/security/ip-policy.ts enforce protocol restrictions, block credentials in URLs, and reject private/reserved IP ranges.
- Redirects are audited rather than blindly followed.
- This means the server never trusts the user-supplied URL as-is, and the browser never directly contacts external PDF hosts.
7. Caching and persistence
- Supabase PostgreSQL is the persistence layer (lib/db/supabase.ts).
- There are two cache layers:
- L1 URL cache in lib/db/analysis-cache.ts, keyed by normalized URL hash.
- L2 content cache keyed by SHA-256 of the PDF bytes.
- lib/db/search-history.ts stores past analyses for history retrieval.
- Cached results are part of the main request path, not a separate background system.
8. AI analysis boundary
- Gemini integration lives in lib/providers/gemini.ts.
- Prompt construction is isolated in lib/analysis/prompt.ts.
- The model is expected to return a strict structured schema defined in lib/analysis/schema.ts, and that response is validated before being accepted.
- The PDF content is treated as untrusted data; the prompt design is meant to reduce prompt injection risk.
9. Validation and error handling
- The app uses lib/errors/app-error.ts and lib/errors/error-response.ts to translate internal failures into public-facing error codes/messages.
- This creates a consistent contract for invalid URLs, unsafe hosts, oversized files, timeouts, rate-limit violations, and model/schema failures.
- The result is a controlled error surface rather than leaking raw exceptions to the client.
10. Rate limiting
- lib/security/rate-limit.ts implements a two-tier quota system.
- The repository indicates separate limits for general request traffic and expensive analysis calls.
- Limits are persisted in the database and keyed via hashed client identifiers to avoid storing raw IPs.
11. Observability
- lib/observability/logger.ts provides server-side logging for analysis and failure paths.
- This is a supporting subsystem rather than a user-facing feature, but it matters for tracing request execution across validation, fetch, cache, and model stages.
12. Architecture decision record trail
- The docs/decisions folder documents the key design choices: monolith structure, SSRF protection, caching strategy, rate limiting, and Gemini schema enforcement.
- These ADRs reinforce the repo’s core shape: a security-heavy server-side document analysis pipeline with strong validation and cache reuse.
Main entry points: analyze/route.ts Analyze API · analyzer Analyzer UI · upload/route.ts Upload API · decisions ADRs
Components 26
UI
Next.js client-side presentation and interaction layer
- App shell · Root layout, page, and global styles for the monolith UI
app/layout.tsx - Analyzer UI · Form, drop zone, skeleton, errors, and result rendering for document analysis
components/analyzer
API
Route handlers that expose the analysis service
- Analyze API · Primary endpoint for URL-based PDF analysis
app/api/analyze/route.ts - Upload API · Direct file upload analysis endpoint
app/api/analyze/upload/route.ts - Cached API · Cache retrieval or cache-backed analysis lookup
app/api/analyze/cached/route.ts - History API · Returns prior analyses for the client
app/api/history/route.ts - Limit API · Exposes rate-limit status to the client
app/api/limit/route.ts
Core pipeline
Server-side validation, ingestion, analysis, caching, and errors
- Request validation · Validates analyze request shape before any work begins
lib/validation/analyze-request.ts - URL transform · Normalizes and prepares submitted URLs for validation and hashing
lib/url/transform-url.ts - URL safety · Blocks unsafe protocols, credentials, and reserved/private hosts
lib/security/validate-url.ts - IP policy · Resolves and rejects disallowed IP ranges during URL checks
lib/security/ip-policy.ts - PDF fetch · Streams remote PDFs from trusted URLs on the server
lib/pdf/fetch-pdf.ts - Upload safety · Validates uploaded PDF size, signature, and trust boundary
lib/pdf/validate-upload.ts - PDF metadata · Derives page count and document metadata
lib/pdf/metadata.ts - Reading time · Computes estimated reading duration from document characteristics
lib/analysis/reading-time.ts - Prompt builder · Constructs the Gemini prompt around untrusted PDF content
lib/analysis/prompt.ts - Analysis schema · Strict response schema required from the model
lib/analysis/schema.ts - Rate limiting · Two-tier request and analysis throttling keyed by hashed client identity
lib/security/rate-limit.ts - App errors · Converts internal failures into controlled public errors
lib/errors/app-error.ts - Error response · Formats safe client-facing error payloads
lib/errors/error-response.ts
Infra
Persistence, observability, and external service integration
- Analysis cache · URL-keyed and content-keyed cached analysis lookup
lib/db/analysis-cache.ts - Search history · Stores prior analyses for history retrieval
lib/db/search-history.ts - Supabase DB · Shared persistence layer for cache, history, and quota state
lib/db/supabase.ts - Gemini provider · Server-side model access for document analysis
lib/providers/gemini.ts - Logger · Server-side logging across validation, fetch, cache, and model paths
lib/observability/logger.ts
Docs
Architecture decision records and design notes
- ADRs · Architecture decision records for monolith, SSRF, caching, rate limits, and schema enforcement
docs/decisions
Connections 36
- App shell → Analyzer UI: renders · The page shell hosts the analyzer components
- Analyzer UI → Analyze API: submits URL · Client sends URL analysis requests to the main API
- Analyzer UI → Upload API: uploads file · Client sends direct PDF uploads to the upload endpoint
- Analyzer UI → Cached API: checks cache · Client can query cache-backed analysis state
- Analyzer UI → History API: loads history · Client requests prior analyses
- Analyzer UI → Limit API: reads quota · Client checks current rate-limit status
- Analyze API → Request validation: validates · Analyze requests are schema-checked first
- Analyze API → URL transform: normalizes · Submitted URLs are normalized before policy checks
- URL transform → URL safety: guards · Transformed URLs are checked for SSRF and trust issues
- URL safety → IP policy: resolves IPs · Disallowed network ranges are rejected
- Analyze API → Rate limiting: throttles · Request traffic is rate-limited before expensive work
- Analyze API → Analysis cache: looks up · Main analysis path consults cached results first
- Analysis cache → Supabase DB: reads/writes · Cache records are persisted in Postgres
- Analyze API → PDF fetch: fetches PDF · Server streams the remote document after validation
- Upload API → Upload safety: validates upload · Upload endpoint enforces size and PDF signature rules
- Upload API → Rate limiting: throttles · Upload analysis is also quota-controlled
- PDF fetch → PDF metadata: extracts metadata · Fetched documents are summarized with deterministic metadata
- Upload safety → PDF metadata: extracts metadata · Validated uploads flow into metadata extraction
- PDF metadata → Reading time: estimates · Metadata feeds reading-time estimation
- Analyze API → Prompt builder: builds prompt · Analysis pipeline constructs a model prompt from document content
- Upload API → Prompt builder: builds prompt · Upload pipeline also constructs the analysis prompt
- Prompt builder → Analysis schema: expects · Prompt is paired with a strict structured response contract
- Prompt builder → Gemini provider: calls · Prompt is sent to the Gemini provider
- Gemini provider → Analysis schema: returns · Model output is validated against the schema before acceptance
- Analyze API → Search history: stores history · Successful analyses are persisted for later retrieval
- Search history → Supabase DB: reads/writes · History records are stored in the database
- History API → Search history: reads · History endpoint serves prior analyses from storage
- Limit API → Rate limiting: reports · Limit endpoint exposes current quota state
- Analyze API → App errors: maps failures · Internal failures are normalized into app errors
- App errors → Error response: formats · Errors are turned into safe API responses
- Analyze API → Logger: logs · Request execution and failures are logged
- Upload API → Logger: logs · Upload path emits server-side logs
- ADRs → Analysis cache: documents · ADR trail captures the caching strategy
- ADRs → URL safety: documents · ADR trail captures SSRF protections
- ADRs → Rate limiting: documents · ADR trail captures rate limiting
- ADRs → Analysis schema: documents · ADR trail captures structured Gemini responses