Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
beb0902
UI aesthetic overhaul to Apple level glassmorphism, schema validation…
pawanchhimwal Jul 27, 2026
94c63f1
docs: add Phase G0 GitHub Integration Architecture specification
pawanchhimwal Jul 28, 2026
8e4c5f2
feat(auth): implement GX-1 GitHub authentication and connection layer
pawanchhimwal Jul 28, 2026
a5442ff
feat(ci-cd-agent): complete phases GX-1 to GX-10 (GitHub OAuth, Autom…
pawanchhimwal Jul 28, 2026
da0f649
fix(vercel): set node engine version to 20.x to resolve vercel build …
pawanchhimwal Jul 28, 2026
171ff28
fix(oauth): resolve GitHub 404 error by canonicalizing redirect_uri t…
pawanchhimwal Jul 28, 2026
f98a47a
fix(dashboard): eliminate all static fallback numbers and query live …
pawanchhimwal Jul 28, 2026
7dcaeda
fix(vercel): set node engine version to 24.x for vercel runtime
pawanchhimwal Jul 28, 2026
9a46fa3
fix(github): handle HTTP 410 expired workflow log retention with user…
pawanchhimwal Jul 28, 2026
02f8c2d
fix(ui): prevent layout overflow by adding min-w-0 to center panel
pawanchhimwal Jul 31, 2026
71c6ca4
feat: redesign workspace with premium apple-like layout
pawanchhimwal Jul 31, 2026
5ec74cd
Update README with CI/CD diagnosis link
pawanchhimwal Jul 31, 2026
43349d1
Delete docs/demo-script
pawanchhimwal Jul 31, 2026
b7af246
chore: revert root README.md and CONTRIBUTING.md to upstream state to…
pawanchhimwal Jul 31, 2026
86c5db0
fix: address CodeRabbit review — security, correctness, and doc fixes
pawanchhimwal Aug 1, 2026
0cff019
fix(history-store): restore toggleHistoryBookmark export name to fix …
pawanchhimwal Aug 1, 2026
fae579b
fix(diagnose): pass IP string to checkRateLimit and use .success prop…
pawanchhimwal Aug 1, 2026
dac3c08
fix(history-store): toggleHistoryBookmark returns updated array inste…
pawanchhimwal Aug 1, 2026
2e51c82
fix(types): add commitMessage to WorkspaceMetadata, fix null handling…
pawanchhimwal Aug 1, 2026
ede4176
Merge branch 'main' into main
pawanchhimwal Aug 1, 2026
fc9c1a6
fix: resolve remaining CodeRabbit review comments
pawanchhimwal Aug 1, 2026
01660a0
perf(health): use HEAD method for GitHub health probe to release resp…
pawanchhimwal Aug 2, 2026
5c1072a
feat: comply with AgentKit repository structure and resolve PR valida…
pawanchhimwal Aug 4, 2026
c24e325
fix(ci-cd-diagnosis-agent): resolve CodeRabbit review feedback across…
pawanchhimwal Aug 4, 2026
4a02bc1
fix(ci-cd-diagnosis-agent): reconcile flow with authentic Lamatic Stu…
pawanchhimwal Aug 4, 2026
002951d
fix(ci-cd-diagnosis-agent): add missing script modules and example lo…
pawanchhimwal Aug 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions kits/ci-cd-diagnosis-agent/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CICD_DIAGNOSIS_FLOW_ID=
LAMATIC_API_KEY=
LAMATIC_API_URL=
LAMATIC_PROJECT_ID=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
SESSION_SECRET=
Comment on lines +1 to +7

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== repository files (target kit) =="
git ls-files 'kits/ci-cd-diagnosis-agent/*' | sed -n '1,200p'

echo
echo "== target files sizes =="
for f in \
  kits/ci-cd-diagnosis-agent/.env.example \
  kits/ci-cd-diagnosis-agent/apps/.env.example \
  kits/ci-cd-diagnosis-agent/README.md \
  kits/ci-cd-diagnosis-agent/agent.md \
  kits/ci-cd-diagnosis-agent/apps/lib/lamatic-client.ts
do
  if [ -f "$f" ]; then
    wc -l "$f"
  else
    echo "MISSING: $f"
  fi
done

echo
echo "== kit root .env.example =="
cat -n kits/ci-cd-diagnosis-agent/.env.example

echo
echo "== apps/.env.example? =="
if [ -f kits/ci-cd-diagnosis-agent/apps/.env.example ]; then
  cat -n kits/ci-cd-diagnosis-agent/apps/.env.example
else
  echo "No apps/.env.example"
fi

echo
echo "== relevant README section =="
sed -n '65,90p' kits/ci-cd-diagnosis-agent/README.md | cat -n

echo
echo "== relevant agent section =="
sed -n '80,95p' kits/ci-cd-diagnosis-agent/agent.md | cat -n

echo
echo "== lamatic client relevant lines =="
sed -n '1,70p' kits/ci-cd-diagnosis-agent/apps/lib/lamatic-client.ts | cat -n

echo
echo "== search for required env variables in target kit =="
rg -n "LAMATIC_API_(URL|KEY|PROJECT_ID)|GITHUB_CLIENT_(ID|SECRET)|SESSION_SECRET|CICD_DIAGNOSIS_FLOW_ID|apps/\.env|\.env\.local|Missing:" kits/ci-cd-diagnosis-agent -S

Repository: Lamatic/AgentKit

Length of output: 10821


Mission: put the app environment contract where setup documents and the app lookup it.

The app needs apps/.env.example to exist and match the root env template requirements. Keep all required values in the app-local contract or update all copy/fill guidance consistently.

  • Add kits/ci-cd-diagnosis-agent/apps/.env.example with all required values.
  • Update README.md and agent.md setup steps so users can copy/fill the app-local file from an existing template.
  • Keep the apps/lib/lamatic-client.ts remediation message after the referenced apps/.env.example is present.
🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 5-5: [UnorderedKey] The GITHUB_CLIENT_ID key should go before the LAMATIC_API_KEY key

(UnorderedKey)


[warning] 6-6: [UnorderedKey] The GITHUB_CLIENT_SECRET key should go before the LAMATIC_API_KEY key

(UnorderedKey)

📍 Affects 4 files
  • kits/ci-cd-diagnosis-agent/.env.example#L1-L7 (this comment)
  • kits/ci-cd-diagnosis-agent/README.md#L72-L83
  • kits/ci-cd-diagnosis-agent/agent.md#L87-L89
  • kits/ci-cd-diagnosis-agent/apps/lib/lamatic-client.ts#L14-L15
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/ci-cd-diagnosis-agent/.env.example` around lines 1 - 7, Ensure
kits/ci-cd-diagnosis-agent/apps/.env.example exists with all required values
from kits/ci-cd-diagnosis-agent/.env.example. Update
kits/ci-cd-diagnosis-agent/README.md lines 72-83 and agent.md lines 87-89 to
instruct users to copy or fill the app-local template, and retain the
apps/lib/lamatic-client.ts remediation reference to apps/.env.example once that
file is present.

Source: Coding guidelines

7 changes: 7 additions & 0 deletions kits/ci-cd-diagnosis-agent/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules/
.next/
.env.local
.env
dist/
*.log
.DS_Store
Comment on lines +1 to +7

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Mission: stop tracking TypeScript compiler cache state.

The generated tsconfig.tsbuildinfo file is committed because the kit does not ignore it.

  • kits/ci-cd-diagnosis-agent/.gitignore#L1-L7: add *.tsbuildinfo.
  • kits/ci-cd-diagnosis-agent/apps/tsconfig.tsbuildinfo#L1-L1: remove this generated file from version control.
📍 Affects 2 files
  • kits/ci-cd-diagnosis-agent/.gitignore#L1-L7 (this comment)
  • kits/ci-cd-diagnosis-agent/apps/tsconfig.tsbuildinfo#L1-L1
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/ci-cd-diagnosis-agent/.gitignore` around lines 1 - 7, Update
kits/ci-cd-diagnosis-agent/.gitignore lines 1-7 to add the *.tsbuildinfo
pattern, and remove the generated
kits/ci-cd-diagnosis-agent/apps/tsconfig.tsbuildinfo file from version control.

19 changes: 19 additions & 0 deletions kits/ci-cd-diagnosis-agent/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Changelog

All notable changes to the **AgentKit CI/CD Diagnosis Agent** will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

---

## [1.0.0] - 2026-07-28

### Added
Comment thread
pawanchhimwal marked this conversation as resolved.

- **GX-1 — GitHub OAuth & Connection Layer**: OAuth 2.0 PKCE authentication with AES-256-GCM sealed cookies.
- **GX-2 — Repository Discovery**: Searchable, sortable, paginated GitHub repository selector.
- **GX-3 — Workflow Discovery**: Actions workflow and failure run discovery with status badges.
- **GX-4 — Automated Log Retrieval & Lamatic Pipeline Integration**: In-memory `.zip` decompression (`fflate`), secret redaction, ANSI stripping, and Lamatic AI diagnosis execution.
- **GX-5 — Copilot Multi-Panel Debugging Workspace**: Apple-glassmorphic workspace with failure timeline, confidence progress ring, interactive log viewer, and report exporter (`.md`, `.json`, `.txt`).
- **GX-6 — Team Command Center**: Repository health metrics, history audit log, bookmarking, and side-by-side failure comparison.
- **GX-7 — Production Hardening & Observability**: OWASP security headers, sliding-window rate limiting, structured JSON logger, and live `/api/health` probes.
- **GX-8 — Open Source & Challenge Submission**: Complete governance documentation, PR templates, and Lamatic AgentKit Challenge presentation pitch scripts.
117 changes: 117 additions & 0 deletions kits/ci-cd-diagnosis-agent/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# ⚡ Autonomous AI CI/CD Diagnosis Agent & Command Center

[![Lamatic AgentKit](https://img.shields.io/badge/Powered%20By-Lamatic%20AgentKit-cyan?style=for-the-badge)](https://lamatic.ai)
[![Next.js 16](https://img.shields.io/badge/Framework-Next.js%2016-black?style=for-the-badge&logo=next.js)](https://nextjs.org)
[![TypeScript](https://img.shields.io/badge/Language-TypeScript-blue?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-emerald?style=for-the-badge)](LICENSE)
[![Build Status](https://img.shields.io/badge/Status-100%25%20Verified%20%26%20Production%20Hardened-emerald?style=for-the-badge)](https://github.com/pawanchhimwal/AgentKit)

An enterprise-grade, autonomous AI CI/CD Diagnosis Agent built with **Lamatic AgentKit**, **Next.js**, **TypeScript**, and **Gemini**. Automatically retrieves failing GitHub Actions workflow execution logs, sanitizes credentials in memory, isolates failure loci, and executes a 8-node RAG diagnostic pipeline to deliver verified root causes, code fixes, and security reviews.

---

## 🌟 Key Capabilities & Highlights

- **⚡ One-Click Automated GitHub Diagnosis**: Connect GitHub OAuth 2.0 PKCE, select a repository and failed workflow run. The agent automatically fetches, unzips in RAM, sanitizes, and diagnoses the failure in seconds.
- **🖥️ Copilot-Style Multi-Panel Debugging Workspace**:
- **Left Sidebar**: Branch, 7-char SHA, runner environment, duration, and triggering actor avatar.
- **Center Panel**: Animated Confidence Ring (`100% Verified`), Root Cause summary, Failure Chronology timeline, and isolated evidence lines.
- **Right Panel**: Syntax-highlighted code fixes with **Copy Code** button, Security Warnings, and RAG Knowledge Base guides.
- **Bottom Explorer**: Collapsible raw terminal log viewer with line numbers, search, and error highlighting (`FATAL`, `Killed`, `exit code 137`).
- **📊 Team Command Center & Audit Log**: Track repository health, failure frequency breakdown, and run side-by-side failure comparisons.
- **📥 Multi-Format Report Export**: One-click export to Markdown (`.md`), JSON (`.json`), Plain Text, or formatted Slack/GitHub PR comment copy.
- **🛡️ Zero-Trust Security & Production Hardened**: Redacts AWS keys & GitHub PATs in memory, enforces OWASP security headers, sliding-window rate limiting, and structured JSON logging.

---

## 🏗️ System Architecture

```mermaid
graph TD
A["👤 Developer / DevOps Engineer"] -->|Connects GitHub / Drops Log| B["⚡ Next.js 16 Frontend App"]
B -->|OAuth 2.0 PKCE / Session Cookie| C["🔑 Auth & Session Guard"]

subgraph GitHub Actions Integration Layer
C -->|List Repos / Workflows| D["🐙 GitHub REST API"]
D -->|Download ZIP Logs| E["📦 Memory Zip Extractor (fflate)"]
E -->|ANSI Stripper & Secret Redactor| F["🧹 Clean Log Locus"]
end

subgraph 8-Node Lamatic AgentKit Pipeline
F -->|POST /api/github/diagnose| G["🧠 Lamatic Cloud AI Engine"]
G --> H["1. Log Cleaner Node"]
H --> I["2. Evidence Extractor Node"]
I --> J["3. Error Classifier Node"]
J --> K["4. RAG Knowledge Retriever"]
K --> L["5. Root Cause Analyzer Node"]
L --> M["6. Fix Generator Node"]
M --> N["7. Fix Verifier Node"]
N --> O["8. Security Reviewer Node"]
end

O -->|Validated JSON Diagnosis| P["💻 Apple-Glassmorphic Multi-Panel Workspace"]
P --> Q["📊 Team Command Center & Analytics Store"]
```

---

## 🚀 Quickstart & Setup Guide

### Prerequisites
- **Node.js**: `>= 20.9.0`
- **npm**: `>= 10.0.0`
- **Lamatic AgentKit Account & API Key**

### 1. Clone & Install Dependencies
```bash
git clone https://github.com/pawanchhimwal/AgentKit.git
cd AgentKit/kits/ci-cd-diagnosis-agent/apps
npm install
```

### 2. Configure Environment Variables
Create `.env.local` in `kits/ci-cd-diagnosis-agent/apps`:
```env
# Lamatic AgentKit Configuration
LAMATIC_API_URL=https://pawansorganization931-soc2readinessauditor578.lamatic.dev
LAMATIC_API_KEY=your_lamatic_api_key_here

# GitHub OAuth App Configuration
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
SESSION_SECRET=32_character_random_secret_string_here
```

### 3. Run Development Server
```bash
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) in your browser.

---

## 📡 API Reference

| Endpoint | Method | Description | Security |
| :--- | :--- | :--- | :--- |
| `GET /api/health` | `GET` | Live health probe for GitHub & Lamatic API connectivity | Public Probe |
| `POST /api/diagnose` | `POST` | Manual log upload AI diagnosis endpoint | Rate-Limited |
| `GET /api/auth/github/login` | `GET` | Initiates GitHub OAuth 2.0 PKCE flow | State Validated |
| `GET /api/github/repos` | `GET` | Discovers user's connected GitHub repositories | Session Cookie |
| `GET /api/github/runs` | `GET` | Fetches workflow runs and failure statuses | Session Cookie |
| `POST /api/github/diagnose` | `POST` | Fetches, unzips, cleans & diagnoses a GitHub Action run | Session Cookie |

---

## 🏆 Lamatic AgentKit Challenge Compliance

This project strictly adheres to all requirements of the **Lamatic AgentKit Challenge**:
- ✅ **Clean Workflow Orchestration**: Implements 10 distinct, specialized AI agent nodes in Lamatic Studio.
- ✅ **Real-World Impact**: Eliminates hours spent manually debugging CI/CD pipeline failures.
- ✅ **Production Quality**: Built with zero disk temporary footprints, structured logging, health probes, and OWASP security headers.

---

## 📜 License

Distributed under the **MIT License**. See `LICENSE` for details.
32 changes: 32 additions & 0 deletions kits/ci-cd-diagnosis-agent/SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Security Policy

The AgentKit CI/CD Diagnosis Agent takes security seriously. As a tool designed to analyze build logs and system execution context, maintaining strict data privacy, credential protection, and threat mitigation is a primary design goal.

---

## 🔒 Security Architecture Guarantees

1. **In-Memory Zero Temporary Footprint**:
- All GitHub Actions `.zip` log extraction occurs directly in RAM using WebAssembly/JS streaming zip decompression (`fflate`).
- Log files are never written to disk or temporary file system storage.

2. **Automated Secret Redaction**:
- Every log stream is passed through a secret sanitizer before reaching the AI model.
- Redacts AWS Access Keys (`AKIA...`), GitHub Personal Access Tokens (`ghp_...`, `github_pat_...`), Bearer authorization headers, and custom user secrets.

3. **Session & Cookie Security**:
- GitHub OAuth sessions are sealed using AES-256-GCM authenticated encryption.
- Session cookies enforce `HttpOnly`, `Secure`, and `SameSite=Lax` protection.

4. **OWASP HTTP Security Headers**:
- Configured with `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and `Permissions-Policy`.

---

## 🐞 Reporting Vulnerabilities

If you discover a potential security vulnerability in this project, please do **NOT** open a public GitHub issue.

Instead, please report security concerns via GitHub's private vulnerability reporting: https://github.com/Lamatic/AgentKit/security/advisories/new

We will acknowledge receipt within 24 hours and provide regular status updates regarding resolution.
102 changes: 102 additions & 0 deletions kits/ci-cd-diagnosis-agent/agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# CI/CD Diagnosis Agent

## Overview

The CI/CD Diagnosis Agent is an AI-powered multi-agent system that analyses GitHub Actions and GitLab CI/CD pipeline failure logs. It orchestrates 10 specialised AI agents through a Lamatic AgentKit DAG to produce a structured, verified diagnosis containing the root cause, an actionable fix, and a risk assessment — in under 30 seconds.

## Purpose

Developers lose hours deciphering cryptic CI/CD logs. This agent automates the entire diagnostic process: it cleans noise, extracts evidence, classifies errors, consults a domain-specific knowledge base (RAG), deduces the root cause, generates a fix, adversarially verifies the fix, and assesses risk — all without human intervention.

## Flow: CICD Diagnosis

### Trigger

The synchronous API Request accepts a raw CI/CD log (`logContent`) and the CI platform (`ciProvider`: `github` or `gitlab`).

### Processing

The 10-node DAG processes the log through the following agents in sequence:

1. **Log Cleaner (Code Node):** Strips timestamps, boilerplate, and redacts secrets via regex.
2. **Evidence Extractor (LLM):** Isolates exact verbatim failure strings (stack traces, exit codes).
3. **Error Classifier (LLM):** Maps evidence to a strict taxonomy (Dependency, Network, Permissions, etc.).
4. **Planner (LLM):** Formulates targeted RAG search queries based on the classification.
5. **Knowledge Retrieval (RAG Node):** Executes hybrid semantic + keyword search over the domain knowledge base.
6. **Root Cause Analyzer (LLM):** Synthesises evidence and retrieved knowledge to deduce the mechanical failure.
7. **Fix Generator (LLM):** Produces executable code snippets or configuration changes.
8. **Fix Verifier (LLM):** Adversarially validates that the fix addresses the root cause.
9. **Risk Reviewer (LLM):** Assesses the fix for security or stability risks.
10. **Output Formatter (Code Node):** Serialises the complete pipeline state into a strict JSON API response.

### Response

The API Response exposes:

- `classification` — Error category and confidence score.
- `analysis` — Root cause summary with verbatim evidence citations.
- `resolution` — Verified code fixes with syntax-highlighted snippets.
- `risk` — Risk level (Low / Medium / High) and security warnings.

### When to Use

Use this agent whenever a GitHub Actions or GitLab CI pipeline fails. It is most effective for:
- Dependency management failures (npm, pip, maven)
- Docker build and runtime failures
- Infrastructure-as-code errors (Terraform)
- Permission and authentication failures
- Network and DNS connectivity issues
- GitHub Actions YAML configuration errors

### Dependencies

- Lamatic synchronous API runtime
- Google Gemini API (configured as the LLM model in the flow)
- A populated RAG Knowledge Base (see `knowledge/` directory)
- The companion Next.js app (`apps/`) for the web interface

## Guardrails

- Never invent log lines not present in the original input.
- Never assume technologies not explicitly mentioned in the evidence.
- Never generate a fix before completing the Root Cause Analysis.
- Never output a fix that introduces `rm -rf`, wildcard IAM policies, or exposed secrets without flagging it as High Risk.
- Always cite exact log lines as evidence for every conclusion.
- Always output valid JSON matching the declared API schema.

## Integration Reference

| Service | Purpose | Credential |
|---|---|---|
| Lamatic API | Executes the deployed diagnosis flow | `LAMATIC_API_KEY` |
| Lamatic project | Selects the project runtime | `LAMATIC_PROJECT_ID`, `LAMATIC_API_URL` |
| Deployed flow | Selects the diagnosis workflow | `CICD_DIAGNOSIS_FLOW_ID` |
| Google Gemini | Powers LLM reasoning (configured in Lamatic) | Stored in Lamatic, never in the app |

## Environment Setup

| Variable | Required | Source | Purpose |
|---|:---:|---|---|
| `LAMATIC_API_KEY` | Yes | Lamatic Settings → API Keys | Authenticates server-side flow execution |
| `LAMATIC_PROJECT_ID` | Yes | Lamatic project settings | Identifies the deployed project |
| `LAMATIC_API_URL` | Yes | Lamatic API Docs | Base endpoint for the project runtime |
| `CICD_DIAGNOSIS_FLOW_ID` | Yes | Flow menu → Copy Flow ID | Identifies the deployed diagnosis flow |

## Quickstart

1. Deploy the Lamatic flow (see `docs/lamatic-workflow.md` for node configuration).
2. Copy `apps/.env.example` to `apps/.env.local`.
3. Fill in the four required Lamatic values.
4. Run `npm install` from the `apps/` directory.
5. Run `npm run dev` and open `http://localhost:3000`.
6. Upload one of the example logs from `examples/` to test the system.

## Common Failure Modes

| Symptom | Likely Cause | Fix |
|---|---|---|
| "Agent is not configured" | Missing environment variables | Compare `.env.local` with `.env.example` |
| Authentication error (401) | Invalid or expired `LAMATIC_API_KEY` | Generate a new key in Lamatic Settings |
| Empty diagnosis / low confidence | RAG knowledge base is not populated | Follow `docs/knowledge-architecture.md` to index documents |
| Slow response (>45s) | Large log file hitting token limits | Reduce log to last 5,000 lines and retry |
| Risk level always "Unknown" | Risk Reviewer node misconfigured | Verify node output schema in Lamatic Studio |
7 changes: 7 additions & 0 deletions kits/ci-cd-diagnosis-agent/apps/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CICD_DIAGNOSIS_FLOW_ID=
LAMATIC_API_KEY=
LAMATIC_API_URL=
LAMATIC_PROJECT_ID=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
SESSION_SECRET=
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { NextRequest, NextResponse } from "next/server";
import { exchangeCodeForAccessToken, fetchGitHubUserProfile, getCanonicalRedirectUri } from "@/lib/auth/github";
import { popOAuthState, setSession } from "@/lib/auth/session";

export async function GET(request: NextRequest) {
const url = new URL(request.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const error = url.searchParams.get("error");
const errorDescription = url.searchParams.get("error_description");

const homeUrl = new URL("/", request.url);

// 1. Handle user cancellation or GitHub OAuth errors
if (error) {
homeUrl.searchParams.set("auth_error", errorDescription || error || "OAuth cancelled");
return NextResponse.redirect(homeUrl);
}

if (!code || !state) {
homeUrl.searchParams.set("auth_error", "Invalid OAuth callback response parameters.");
return NextResponse.redirect(homeUrl);
}

// 2. CSRF State Validation
const savedState = await popOAuthState();
if (!savedState || savedState !== state) {
homeUrl.searchParams.set("auth_error", "CSRF state validation failed. Please try logging in again.");
return NextResponse.redirect(homeUrl);
}

// 3. Exchange Code for Access Token using canonical redirect URI
const redirectUri = getCanonicalRedirectUri(request.headers, url.origin);
const tokenResult = await exchangeCodeForAccessToken(code, redirectUri);

if ("error" in tokenResult) {
homeUrl.searchParams.set("auth_error", tokenResult.error);
return NextResponse.redirect(homeUrl);
}

// 4. Fetch User Profile (wrapped to handle network failures gracefully)
let profile: Awaited<ReturnType<typeof fetchGitHubUserProfile>>;
try {
profile = await fetchGitHubUserProfile(tokenResult.accessToken);
} catch {
homeUrl.searchParams.set("auth_error", "Failed to fetch GitHub user profile. Please try again.");
return NextResponse.redirect(homeUrl);
}

if (!profile) {
homeUrl.searchParams.set("auth_error", "Failed to fetch GitHub user profile.");
return NextResponse.redirect(homeUrl);
}

// 5. Seal Session into HTTP-only cookie (wrapped to handle cookie write failures)
try {
await setSession({
accessToken: tokenResult.accessToken,
user: {
login: profile.login,
avatarUrl: profile.avatar_url,
name: profile.name || undefined,
email: profile.email || undefined,
},
});
} catch {
homeUrl.searchParams.set("auth_error", "Failed to establish a secure session. Please try again.");
return NextResponse.redirect(homeUrl);
}

// 6. Redirect back to homepage on success
homeUrl.searchParams.set("auth_success", "true");
return NextResponse.redirect(homeUrl);
}
Loading
Loading