diff --git a/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx new file mode 100644 index 00000000..51b37102 --- /dev/null +++ b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/github/page.tsx @@ -0,0 +1,267 @@ +'use client'; + +import { use } from 'react'; +import { FaGithub, FaCodeBranch, FaCircleNotch, FaExclamationCircle, FaExternalLinkAlt, FaSyncAlt } from 'react-icons/fa'; +import { useAuth } from '@/lib/hooks/useAuth'; +import { useGitHubData } from '@/lib/hooks/useGitHubData'; +import { useGitHubIntegration } from '@/lib/hooks/useGitHubIntegration'; + +export default function GitHubPage({ params }: { params: Promise<{ projectId: string }> }) { + const { projectId } = use(params); + const { userId, isLoading: authLoading, error: authError } = useAuth(); + const { patStatus, isLoading: patLoading } = useGitHubIntegration(projectId); + const { pullRequests, issues, isLoading: dataLoading, error, refetch } = useGitHubData(projectId, { state: 'open' }); + + const isLoading = authLoading || patLoading || dataLoading; + + if (authLoading || patLoading) { + return ( +
+

Loading...

+
+ ); + } + + if (authError || !userId) { + return ( +
+

Please sign in to view this page

+
+ ); + } + + if (!patStatus?.hasPAT) { + return ( + <> +
+

GitHub

+

View pull requests and issues from your repository

+
+ +
+
+ +

GitHub not connected

+

+ Connect your GitHub repository in settings to view pull requests and issues here. +

+ + Go to Settings + +
+
+ + ); + } + + return ( + <> +
+
+
+

GitHub

+

View pull requests and issues from your repository

+
+ +
+
+ + {error && ( +
+

{error}

+
+ )} + +
+ {/* Pull Requests */} +
+
+
+ +

Pull Requests

+ + {pullRequests.length} open + +
+
+
+ {isLoading ? ( +
+ +

Loading pull requests...

+
+ ) : pullRequests.length === 0 ? ( +
+

No open pull requests

+
+ ) : ( + pullRequests.map((pr) => ( + +
+
+
+ + {pr.title} + + {pr.draft && ( + + Draft + + )} +
+
+ #{pr.number} + opened {new Date(pr.created_at).toLocaleDateString()} + by {pr.user.login} +
+ {pr.labels.length > 0 && ( +
+ {pr.labels.slice(0, 3).map((label) => ( + + {label.name} + + ))} + {pr.labels.length > 3 && ( + +{pr.labels.length - 3} + )} +
+ )} +
+ +
+
+ )) + )} +
+
+ + {/* Issues */} +
+
+
+ +

Issues

+ + {issues.length} open + +
+
+
+ {isLoading ? ( +
+ +

Loading issues...

+
+ ) : issues.length === 0 ? ( +
+

No open issues

+
+ ) : ( + issues.map((issue) => ( + +
+
+
+ + {issue.title} + +
+
+ #{issue.number} + opened {new Date(issue.created_at).toLocaleDateString()} + by {issue.user.login} +
+ {issue.labels.length > 0 && ( +
+ {issue.labels.slice(0, 3).map((label) => ( + + {label.name} + + ))} + {issue.labels.length > 3 && ( + +{issue.labels.length - 3} + )} +
+ )} + {issue.assignees.length > 0 && ( +
+ {issue.assignees.slice(0, 3).map((assignee) => ( + {assignee.login} + ))} + {issue.assignees.length > 3 && ( + + +{issue.assignees.length - 3} + + )} +
+ )} +
+ +
+
+ )) + )} +
+
+
+ + {/* Repo link */} + {patStatus?.githubUrl && ( +
+ + + View repository on GitHub + + +
+ )} + + ); +} diff --git a/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/settings/page.tsx b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/settings/page.tsx index df6153c7..a29f80c0 100644 --- a/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/settings/page.tsx +++ b/src/app/(portal)/portal/projects/(with-sidebar)/[projectId]/settings/page.tsx @@ -1,7 +1,10 @@ 'use client'; import { use, useEffect, useRef, useState } from 'react'; +import { FaGithub, FaEye, FaEyeSlash, FaCheck, FaExclamationTriangle, FaTrash } from 'react-icons/fa'; import { useAuth } from '@/lib/hooks/useAuth'; +import { useUserRole } from '@/lib/hooks/useUserRole'; +import { useGitHubIntegration } from '@/lib/hooks/useGitHubIntegration'; import { getProjectById, updateProjectSettings, uploadProjectLogo } from '@/lib/supabase/projectService'; import { Project } from '@/types/project'; @@ -20,6 +23,10 @@ const LINK_FIELDS: SettingsField[] = [ export default function SettingsPage({ params }: { params: Promise<{ projectId: string }> }) { const { projectId } = use(params); const { userId, isLoading: authLoading, error: authError } = useAuth(); + const { canPostEvents, isLoading: roleLoading } = useUserRole(projectId, userId); + + // Determine if user is project lead based on canPostEvents permission + const isProjectLead = canPostEvents; const [project, setProject] = useState(null); const [projectLoading, setProjectLoading] = useState(true); @@ -35,6 +42,22 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: const [saving, setSaving] = useState(false); const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle'); + // GitHub integration state + const [showPATInput, setShowPATInput] = useState(false); + const [patValue, setPatValue] = useState(''); + const [showPAT, setShowPAT] = useState(false); + const [patSaving, setPatSaving] = useState(false); + const [patError, setPatError] = useState(null); + const [patSuccess, setPatSuccess] = useState(null); + + const { + patStatus, + isLoading: patStatusLoading, + savePAT, + removePAT, + refreshStatus, + } = useGitHubIntegration(projectId); + useEffect(() => { if (!projectId) return; const load = async () => { @@ -82,11 +105,57 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: if (updated) { setProject(updated); + // Refresh GitHub integration status in case githubUrl changed + refreshStatus(); setTimeout(() => setSaveStatus('idle'), 3000); } }; - if (authLoading || projectLoading) { + const handleSavePAT = async () => { + if (!patValue.trim()) { + setPatError('Please enter a valid GitHub Personal Access Token'); + return; + } + + setPatSaving(true); + setPatError(null); + setPatSuccess(null); + + const result = await savePAT(patValue); + + setPatSaving(false); + + if (result.success) { + setPatSuccess('GitHub token saved successfully!'); + setPatValue(''); + setShowPATInput(false); + setTimeout(() => setPatSuccess(null), 3000); + } else { + setPatError(result.error ?? 'Failed to save token'); + } + }; + + const handleRemovePAT = async () => { + if (!confirm('Are you sure you want to remove the GitHub integration? You will need to re-add the token to view PRs and issues.')) { + return; + } + + setPatSaving(true); + setPatError(null); + + const result = await removePAT(); + + setPatSaving(false); + + if (result.success) { + setPatSuccess('GitHub token removed'); + setTimeout(() => setPatSuccess(null), 3000); + } else { + setPatError(result.error ?? 'Failed to remove token'); + } + }; + + if (authLoading || projectLoading || roleLoading) { return (

Loading...

@@ -134,7 +203,7 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: Upload image {logoPreview && logoPreview !== (project?.logoUrl ?? null) && ( -

New logo selected — save to apply

+

New logo selected - save to apply

)}

PNG, JPG, SVG up to 5 MB

@@ -151,17 +220,17 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: {/* Links */}

Project Links

- {LINK_FIELDS.map(({ key, label, placeholder }) => { - const value = key === 'githubUrl' ? githubUrl : key === 'figmaUrl' ? figmaUrl : notionUrl; - const setter = key === 'githubUrl' ? setGithubUrl : key === 'figmaUrl' ? setFigmaUrl : setNotionUrl; + {LINK_FIELDS.map((field) => { + const value = field.key === 'githubUrl' ? githubUrl : field.key === 'figmaUrl' ? figmaUrl : notionUrl; + const setter = field.key === 'githubUrl' ? setGithubUrl : field.key === 'figmaUrl' ? setFigmaUrl : setNotionUrl; return ( -
- +
+ setter(e.target.value)} - placeholder={placeholder} + placeholder={field.placeholder} className="w-full rounded-lg border border-[#D4D7E5] px-3 py-2 text-sm text-black placeholder:text-black/30 focus:outline-none focus:ring-2 focus:ring-[#3F86FF]/40" />
@@ -169,6 +238,161 @@ export default function SettingsPage({ params }: { params: Promise<{ projectId: })}
+ {/* GitHub Integration */} +
+
+ +

GitHub Integration

+
+ + {patStatusLoading ? ( +

Loading GitHub status...

+ ) : patStatus?.hasPAT ? ( +
+
+ + Repository connected +
+ + {patStatus.githubUrl && ( +

+ Connected to:{' '} + + {patStatus.githubUrl} + +

+ )} + + {patStatus.updatedAt && ( +

+ Token last updated: {new Date(patStatus.updatedAt).toLocaleDateString()} +

+ )} + + {isProjectLead && ( +
+ + +
+ )} +
+ ) : ( +
+

+ Connect your GitHub repository to view pull requests and issues in your project dashboard. +

+ + {isProjectLead ? ( + <> + {!patStatus?.githubUrl && ( +
+ + Please set a GitHub URL in the Project Links section above first. +
+ )} + + + + ) : ( +

+ Only project leads can configure the GitHub integration. +

+ )} +
+ )} + + {/* PAT Input Form */} + {showPATInput && isProjectLead && ( +
+
+ +
+ setPatValue(e.target.value)} + placeholder="ghp_xxxxxxxxxxxx" + className="w-full rounded-lg border border-[#D4D7E5] px-3 py-2 pr-10 text-sm text-black placeholder:text-black/30 focus:outline-none focus:ring-2 focus:ring-[#3F86FF]/40" + /> + +
+

+ Create a token with repo scope at{' '} + + GitHub Settings + +

+
+ + {patError &&

{patError}

} + +
+ + +
+
+ )} + + {patSuccess &&

{patSuccess}

} +
+ {/* Save */}
{saveStatus === 'success' && (

Changes saved!

diff --git a/src/app/api/projects/[projectId]/github/issues/route.ts b/src/app/api/projects/[projectId]/github/issues/route.ts new file mode 100644 index 00000000..a950935c --- /dev/null +++ b/src/app/api/projects/[projectId]/github/issues/route.ts @@ -0,0 +1,72 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { isProjectMember } from '@/lib/utils/authorization'; +import { fetchIssues, parseGitHubUrl } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + if (!project) { + return NextResponse.json({ error: 'Project not found' }, { status: 404 }); + } + + if (!project.github_pat_encrypted) { + return NextResponse.json({ error: 'GitHub not connected' }, { status: 400 }); + } + + if (!project.githubUrl) { + return NextResponse.json({ error: 'No GitHub URL configured' }, { status: 400 }); + } + + const parsed = parseGitHubUrl(project.githubUrl); + if (!parsed) { + return NextResponse.json({ error: 'Invalid GitHub URL' }, { status: 400 }); + } + + const { owner, repo } = parsed; + + const { searchParams } = new URL(request.url); + const state = (searchParams.get('state') as 'open' | 'closed' | 'all') ?? 'open'; + const perPage = parseInt(searchParams.get('per_page') ?? '30', 10); + + const { data, error } = await fetchIssues(owner, repo, project.github_pat_encrypted, { + state, + per_page: Math.min(perPage, 100), + }); + + if (error) { + return NextResponse.json({ error: error.message }, { status: error.status ?? 500 }); + } + + return NextResponse.json({ data }); + } catch (error) { + console.error('Error fetching issues:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/app/api/projects/[projectId]/github/pat/route.ts b/src/app/api/projects/[projectId]/github/pat/route.ts new file mode 100644 index 00000000..d23c6267 --- /dev/null +++ b/src/app/api/projects/[projectId]/github/pat/route.ts @@ -0,0 +1,138 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { encryptPAT } from '@/lib/utils/encryption'; +import { isProjectLead, isProjectMember } from '@/lib/utils/authorization'; +import { validateGitHubPAT } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +/** + * GET - Check if PAT is configured (returns only status, not the token) + */ +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, github_pat_updated_at, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + return NextResponse.json({ + hasPAT: !!project?.github_pat_encrypted, + updatedAt: project?.github_pat_updated_at ?? null, + githubUrl: project?.githubUrl ?? null, + }); + } catch (error) { + console.error('Error checking PAT status:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} + +/** + * POST - Save or update the PAT + */ +export async function POST(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const leadCheck = await isProjectLead(user.id, projectId); + if (!leadCheck) { + return NextResponse.json({ error: 'Only project leads can configure GitHub integration' }, { status: 403 }); + } + + const body = await request.json(); + const { pat } = body; + + if (!pat || typeof pat !== 'string') { + return NextResponse.json({ error: 'PAT is required' }, { status: 400 }); + } + + const validation = await validateGitHubPAT(pat); + if (!validation.valid) { + return NextResponse.json({ error: validation.error ?? 'Invalid PAT' }, { status: 400 }); + } + + const encryptedPAT = encryptPAT(pat); + + const { error: updateError } = await supabase + .from('projects') + .update({ + github_pat_encrypted: encryptedPAT, + github_pat_updated_at: new Date().toISOString(), + }) + .eq('id', projectId); + + if (updateError) { + console.error('Error saving PAT:', updateError); + return NextResponse.json({ error: 'Failed to save PAT' }, { status: 500 }); + } + + return NextResponse.json({ success: true, message: 'GitHub token saved successfully' }); + } catch (error) { + console.error('Error saving PAT:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} + +/** + * DELETE - Remove the PAT + */ +export async function DELETE(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const leadCheck = await isProjectLead(user.id, projectId); + if (!leadCheck) { + return NextResponse.json({ error: 'Only project leads can remove GitHub integration' }, { status: 403 }); + } + + const { error: updateError } = await supabase + .from('projects') + .update({ + github_pat_encrypted: null, + github_pat_updated_at: null, + }) + .eq('id', projectId); + + if (updateError) { + console.error('Error removing PAT:', updateError); + return NextResponse.json({ error: 'Failed to remove PAT' }, { status: 500 }); + } + + return NextResponse.json({ success: true, message: 'GitHub token removed' }); + } catch (error) { + console.error('Error removing PAT:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/app/api/projects/[projectId]/github/pulls/route.ts b/src/app/api/projects/[projectId]/github/pulls/route.ts new file mode 100644 index 00000000..6678cd94 --- /dev/null +++ b/src/app/api/projects/[projectId]/github/pulls/route.ts @@ -0,0 +1,72 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { createClient } from '@/lib/supabase/server'; +import { isProjectMember } from '@/lib/utils/authorization'; +import { fetchPullRequests, parseGitHubUrl } from '@/lib/services/githubService'; + +interface RouteParams { + params: Promise<{ projectId: string }>; +} + +export async function GET(request: NextRequest, { params }: RouteParams) { + try { + const { projectId } = await params; + const supabase = await createClient(); + + const { data: { user }, error: authError } = await supabase.auth.getUser(); + if (authError || !user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const memberCheck = await isProjectMember(user.id, projectId); + if (!memberCheck) { + return NextResponse.json({ error: 'Not a project member' }, { status: 403 }); + } + + const { data: project, error: projectError } = await supabase + .from('projects') + .select('github_pat_encrypted, githubUrl') + .eq('id', projectId) + .single(); + + if (projectError) { + return NextResponse.json({ error: 'Database error' }, { status: 500 }); + } + + if (!project) { + return NextResponse.json({ error: 'Project not found' }, { status: 404 }); + } + + if (!project.github_pat_encrypted) { + return NextResponse.json({ error: 'GitHub not connected' }, { status: 400 }); + } + + if (!project.githubUrl) { + return NextResponse.json({ error: 'No GitHub URL configured' }, { status: 400 }); + } + + const parsed = parseGitHubUrl(project.githubUrl); + if (!parsed) { + return NextResponse.json({ error: 'Invalid GitHub URL' }, { status: 400 }); + } + + const { owner, repo } = parsed; + + const { searchParams } = new URL(request.url); + const state = (searchParams.get('state') as 'open' | 'closed' | 'all') ?? 'open'; + const perPage = parseInt(searchParams.get('per_page') ?? '30', 10); + + const { data, error } = await fetchPullRequests(owner, repo, project.github_pat_encrypted, { + state, + per_page: Math.min(perPage, 100), + }); + + if (error) { + return NextResponse.json({ error: error.message }, { status: error.status ?? 500 }); + } + + return NextResponse.json({ data }); + } catch (error) { + console.error('Error fetching PRs:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} diff --git a/src/components/portal/project/MembershipPortalSidebar.tsx b/src/components/portal/project/MembershipPortalSidebar.tsx index 4727f359..112159e7 100644 --- a/src/components/portal/project/MembershipPortalSidebar.tsx +++ b/src/components/portal/project/MembershipPortalSidebar.tsx @@ -10,6 +10,7 @@ import { RxFileText, RxGear, } from "react-icons/rx"; +import { FaGithub } from "react-icons/fa"; export type MembershipPortalSidebarItem = { id: string; @@ -35,6 +36,7 @@ const BASE_ITEMS = [ { id: "overview", label: "Overview", path: "overview", icon: RxHome }, { id: "board", label: "Board", path: "board", icon: RxDashboard }, { id: "list", label: "List", path: "list", icon: RxRows }, + { id: "github", label: "GitHub", path: "github", icon: FaGithub }, { id: "members", label: "Members", path: "members", icon: RxPerson }, { id: "docs", label: "Docs", path: "docs", icon: RxFileText }, { id: "settings", label: "Settings", path: "settings", icon: RxGear }, diff --git a/src/lib/hooks/useGitHubData.ts b/src/lib/hooks/useGitHubData.ts new file mode 100644 index 00000000..280fb141 --- /dev/null +++ b/src/lib/hooks/useGitHubData.ts @@ -0,0 +1,105 @@ +import { useState, useEffect, useCallback } from 'react'; + +interface GitHubPullRequest { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + merged_at: string | null; + user: { login: string; avatar_url: string }; + labels: Array<{ name: string; color: string }>; + draft: boolean; +} + +interface GitHubIssue { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + user: { login: string; avatar_url: string }; + labels: Array<{ name: string; color: string }>; + assignees: Array<{ login: string; avatar_url: string }>; +} + +interface UseGitHubDataReturn { + pullRequests: GitHubPullRequest[]; + issues: GitHubIssue[]; + isLoading: boolean; + error: string | null; + refetch: () => void; +} + +export function useGitHubData( + projectId: string | null, + options?: { state?: 'open' | 'closed' | 'all' } +): UseGitHubDataReturn { + const [pullRequests, setPullRequests] = useState([]); + const [issues, setIssues] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const fetchData = useCallback(async () => { + if (!projectId) return; + + setIsLoading(true); + setError(null); + + try { + const state = options?.state ?? 'open'; + + const [prResponse, issuesResponse] = await Promise.all([ + fetch(`/api/projects/${projectId}/github/pulls?state=${state}`), + fetch(`/api/projects/${projectId}/github/issues?state=${state}`), + ]); + + if (prResponse.ok) { + const prData = await prResponse.json(); + setPullRequests(prData.data ?? []); + } else { + const prError = await prResponse.json(); + setPullRequests([]); + setError(prError.error || 'Failed to fetch pull requests'); + } + + if (issuesResponse.ok) { + const issuesData = await issuesResponse.json(); + setIssues(issuesData.data ?? []); + } else { + const issuesError = await issuesResponse.json(); + setIssues([]); + if (!error) { + setError(issuesError.error || 'Failed to fetch issues'); + } + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch GitHub data'); + setPullRequests([]); + setIssues([]); + } finally { + setIsLoading(false); + } + }, [projectId, options?.state, error]); + + useEffect(() => { + fetchData(); + }, [fetchData]); + + return { + pullRequests, + issues, + isLoading, + error, + refetch: fetchData, + }; +} + +export type { GitHubPullRequest, GitHubIssue }; diff --git a/src/lib/hooks/useGitHubIntegration.ts b/src/lib/hooks/useGitHubIntegration.ts new file mode 100644 index 00000000..aaf04337 --- /dev/null +++ b/src/lib/hooks/useGitHubIntegration.ts @@ -0,0 +1,105 @@ +import { useState, useEffect, useCallback } from 'react'; + +interface PATStatus { + hasPAT: boolean; + updatedAt: string | null; + githubUrl: string | null; +} + +interface UseGitHubIntegrationReturn { + patStatus: PATStatus | null; + isLoading: boolean; + error: string | null; + savePAT: (pat: string) => Promise<{ success: boolean; error?: string }>; + removePAT: () => Promise<{ success: boolean; error?: string }>; + refreshStatus: () => Promise; +} + +export function useGitHubIntegration(projectId: string | null): UseGitHubIntegrationReturn { + const [patStatus, setPatStatus] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const fetchStatus = useCallback(async () => { + if (!projectId) return; + + setIsLoading(true); + setError(null); + + try { + const response = await fetch(`/api/projects/${projectId}/github/pat`); + const data = await response.json(); + + if (!response.ok) { + throw new Error(data.error ?? 'Failed to fetch GitHub status'); + } + + setPatStatus(data); + } catch (err) { + setError(err instanceof Error ? err.message : 'Unknown error'); + } finally { + setIsLoading(false); + } + }, [projectId]); + + useEffect(() => { + fetchStatus(); + }, [fetchStatus]); + + const savePAT = useCallback(async (pat: string): Promise<{ success: boolean; error?: string }> => { + if (!projectId) { + return { success: false, error: 'No project selected' }; + } + + try { + const response = await fetch(`/api/projects/${projectId}/github/pat`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ pat }), + }); + + const data = await response.json(); + + if (!response.ok) { + return { success: false, error: data.error ?? 'Failed to save PAT' }; + } + + await fetchStatus(); + return { success: true }; + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } + }, [projectId, fetchStatus]); + + const removePAT = useCallback(async (): Promise<{ success: boolean; error?: string }> => { + if (!projectId) { + return { success: false, error: 'No project selected' }; + } + + try { + const response = await fetch(`/api/projects/${projectId}/github/pat`, { + method: 'DELETE', + }); + + const data = await response.json(); + + if (!response.ok) { + return { success: false, error: data.error ?? 'Failed to remove PAT' }; + } + + await fetchStatus(); + return { success: true }; + } catch (err) { + return { success: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } + }, [projectId, fetchStatus]); + + return { + patStatus, + isLoading, + error, + savePAT, + removePAT, + refreshStatus: fetchStatus, + }; +} diff --git a/src/lib/services/githubService.ts b/src/lib/services/githubService.ts new file mode 100644 index 00000000..cf2e967c --- /dev/null +++ b/src/lib/services/githubService.ts @@ -0,0 +1,168 @@ +import { decryptPAT } from '@/lib/utils/encryption'; + +export interface GitHubPullRequest { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + merged_at: string | null; + user: { + login: string; + avatar_url: string; + }; + labels: Array<{ name: string; color: string }>; + draft: boolean; +} + +export interface GitHubIssue { + id: number; + number: number; + title: string; + state: 'open' | 'closed'; + html_url: string; + body: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + user: { + login: string; + avatar_url: string; + }; + labels: Array<{ name: string; color: string }>; + assignees: Array<{ login: string; avatar_url: string }>; +} + +export interface GitHubApiError { + message: string; + status?: number; +} + +/** + * Parse owner/repo from a GitHub URL + */ +export function parseGitHubUrl(url: string): { owner: string; repo: string } | null { + const match = url.match(/github\.com\/([^/]+)\/([^/]+)/); + if (!match) return null; + return { owner: match[1], repo: match[2].replace('.git', '') }; +} + +/** + * Fetch pull requests from GitHub API + */ +export async function fetchPullRequests( + owner: string, + repo: string, + encryptedPAT: string, + options?: { state?: 'open' | 'closed' | 'all'; per_page?: number } +): Promise<{ data: GitHubPullRequest[] | null; error: GitHubApiError | null }> { + try { + const pat = decryptPAT(encryptedPAT); + const state = options?.state ?? 'open'; + const perPage = options?.per_page ?? 30; + + const response = await fetch( + `https://api.github.com/repos/${owner}/${repo}/pulls?state=${state}&per_page=${perPage}&sort=updated`, + { + headers: { + 'Authorization': `Bearer ${pat}`, + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + } + ); + + if (!response.ok) { + if (response.status === 401) { + return { data: null, error: { message: 'Invalid or expired GitHub token', status: 401 } }; + } + if (response.status === 403) { + return { data: null, error: { message: 'GitHub API rate limit exceeded', status: 403 } }; + } + if (response.status === 404) { + return { data: null, error: { message: 'Repository not found or no access', status: 404 } }; + } + return { data: null, error: { message: `GitHub API error: ${response.status}`, status: response.status } }; + } + + const data = await response.json(); + return { data, error: null }; + } catch (err) { + return { data: null, error: { message: err instanceof Error ? err.message : 'Unknown error' } }; + } +} + +/** + * Fetch issues from GitHub API + */ +export async function fetchIssues( + owner: string, + repo: string, + encryptedPAT: string, + options?: { state?: 'open' | 'closed' | 'all'; per_page?: number } +): Promise<{ data: GitHubIssue[] | null; error: GitHubApiError | null }> { + try { + const pat = decryptPAT(encryptedPAT); + const state = options?.state ?? 'open'; + const perPage = options?.per_page ?? 30; + + const response = await fetch( + `https://api.github.com/repos/${owner}/${repo}/issues?state=${state}&per_page=${perPage}&sort=updated`, + { + headers: { + 'Authorization': `Bearer ${pat}`, + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + } + ); + + if (!response.ok) { + if (response.status === 401) { + return { data: null, error: { message: 'Invalid or expired GitHub token', status: 401 } }; + } + if (response.status === 403) { + return { data: null, error: { message: 'GitHub API rate limit exceeded', status: 403 } }; + } + if (response.status === 404) { + return { data: null, error: { message: 'Repository not found or no access', status: 404 } }; + } + return { data: null, error: { message: `GitHub API error: ${response.status}`, status: response.status } }; + } + + const data = await response.json(); + // Filter out pull requests (GitHub includes PRs in issues endpoint) + const issues = data.filter((item: { pull_request?: unknown }) => !item.pull_request); + return { data: issues, error: null }; + } catch (err) { + return { data: null, error: { message: err instanceof Error ? err.message : 'Unknown error' } }; + } +} + +/** + * Validate a GitHub PAT by making a test API call + */ +export async function validateGitHubPAT(pat: string): Promise<{ valid: boolean; error?: string }> { + try { + const response = await fetch('https://api.github.com/user', { + headers: { + 'Authorization': `Bearer ${pat}`, + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + }); + + if (response.ok) { + return { valid: true }; + } + if (response.status === 401) { + return { valid: false, error: 'Invalid token' }; + } + return { valid: false, error: `Validation failed: ${response.status}` }; + } catch (err) { + return { valid: false, error: err instanceof Error ? err.message : 'Unknown error' }; + } +} diff --git a/src/lib/utils/authorization.ts b/src/lib/utils/authorization.ts new file mode 100644 index 00000000..16493444 --- /dev/null +++ b/src/lib/utils/authorization.ts @@ -0,0 +1,45 @@ +import { createClient } from '@/lib/supabase/server'; + +/** + * Check if a user is a project lead for a specific project + */ +export async function isProjectLead(userId: string, projectId: string): Promise { + const supabase = await createClient(); + + const { data, error } = await supabase + .from('project_members') + .select('rbac_role:roles!project_members_rbac_role_id_fkey(name)') + .eq('project_id', projectId) + .eq('user_id', userId) + .single(); + + if (error || !data) { + return false; + } + + // Handle the rbac_role which can be an object or array from Supabase + const rbacRole = data.rbac_role as unknown; + let roleName: string | undefined; + + if (rbacRole && typeof rbacRole === 'object' && !Array.isArray(rbacRole)) { + roleName = (rbacRole as { name?: string }).name; + } + + return roleName?.toLowerCase() === 'project lead'; +} + +/** + * Check if a user is a member of a specific project + */ +export async function isProjectMember(userId: string, projectId: string): Promise { + const supabase = await createClient(); + + const { data, error } = await supabase + .from('project_members') + .select('id') + .eq('project_id', projectId) + .eq('user_id', userId) + .single(); + + return !error && !!data; +} diff --git a/src/lib/utils/encryption.ts b/src/lib/utils/encryption.ts new file mode 100644 index 00000000..511dc2bf --- /dev/null +++ b/src/lib/utils/encryption.ts @@ -0,0 +1,57 @@ +import crypto from 'crypto'; + +const ALGORITHM = 'aes-256-gcm'; +const IV_LENGTH = 16; +const AUTH_TAG_LENGTH = 16; + +function getEncryptionKey(): Buffer { + const key = process.env.GITHUB_PAT_ENCRYPTION_KEY; + if (!key) { + throw new Error('GITHUB_PAT_ENCRYPTION_KEY environment variable is not set'); + } + return Buffer.from(key, 'hex'); +} + +/** + * Encrypts a GitHub PAT using AES-256-GCM + * Returns a base64-encoded string containing IV + auth tag + encrypted data + */ +export function encryptPAT(plaintext: string): string { + const key = getEncryptionKey(); + const iv = crypto.randomBytes(IV_LENGTH); + const cipher = crypto.createCipheriv(ALGORITHM, key, iv); + + let encrypted = cipher.update(plaintext, 'utf8', 'base64'); + encrypted += cipher.final('base64'); + + const authTag = cipher.getAuthTag(); + + // Combine IV + auth tag + encrypted data + const combined = Buffer.concat([ + iv, + authTag, + Buffer.from(encrypted, 'base64') + ]); + + return combined.toString('base64'); +} + +/** + * Decrypts a GitHub PAT that was encrypted with encryptPAT + */ +export function decryptPAT(encryptedData: string): string { + const key = getEncryptionKey(); + const combined = Buffer.from(encryptedData, 'base64'); + + const iv = combined.subarray(0, IV_LENGTH); + const authTag = combined.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH); + const encrypted = combined.subarray(IV_LENGTH + AUTH_TAG_LENGTH); + + const decipher = crypto.createDecipheriv(ALGORITHM, key, iv); + decipher.setAuthTag(authTag); + + let decrypted = decipher.update(encrypted, undefined, 'utf8'); + decrypted += decipher.final('utf8'); + + return decrypted; +} diff --git a/src/types/project.ts b/src/types/project.ts index 2f8aaaa5..479924ba 100644 --- a/src/types/project.ts +++ b/src/types/project.ts @@ -14,4 +14,7 @@ export interface Project { prototypeUrl?: string; demoDayUrl?: string; instaPostUrl?: string; + // GitHub integration fields + github_pat_encrypted?: string | null; + github_pat_updated_at?: string | null; }