All files / src/services github-verification-service.ts

88.12% Statements 245/278
85.71% Branches 36/42
100% Functions 7/7
88.12% Lines 245/278

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 2791x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 13x 13x 13x 15x 11x 11x 11x 11x 11x 2x 2x 15x 1x 1x 1x 15x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 10x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 1x 1x 1x 1x 1x 1x 4x 4x 4x 10x 2x 2x 1x 1x 1x 1x     4x 4x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 10x             10x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 9x 1x 1x 1x                                   9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 2x 2x  
import * as vscode from 'vscode';
 
/**
 * Service for verifying GitHub repository access permissions
 * Used to ensure team creators have push access to the repositories they're linking
 */
 
export interface GitHubRepoInfo {
    owner: string;
    repo: string;
    fullName: string;  // e.g., "microsoft/vscode"
    repoId: number;
    htmlUrl: string;
}
 
export interface GitHubPermissionCheck {
    hasAccess: boolean;
    permission?: string;  // 'admin', 'write', 'read', 'none'
    repoInfo?: GitHubRepoInfo;
    error?: string;
}
 
/**
 * Extracts owner and repo name from a GitHub repository URL
 * Supports both HTTPS and SSH formats
 */
export function parseGitHubRepoUrl(url: string): { owner: string; repo: string } | null {
    try {
        // Normalize the URL
        let normalized = url.trim();
 
        // Handle SSH format: git@github.com:owner/repo.git
        const sshMatch = normalized.match(/git@github\.com:([^\/]+)\/(.+?)(?:\.git)?$/);
        if (sshMatch) {
            return {
                owner: sshMatch[1],
                repo: sshMatch[2].replace(/\.git$/, '')
            };
        }
 
        // Handle HTTPS format: https://github.com/owner/repo or https://github.com/owner/repo.git
        const httpsMatch = normalized.match(/(?:https?:\/\/)?github\.com\/([^\/]+)\/(.+?)(?:\.git)?$/);
        if (httpsMatch) {
            return {
                owner: httpsMatch[1],
                repo: httpsMatch[2].replace(/\.git$/, '')
            };
        }
 
        return null;
    } catch (error) {
        console.error('[GitHub Verification] Error parsing repo URL:', error);
        return null;
    }
}
 
/**
 * Checks if the authenticated user has push access to a GitHub repository
 * Uses Supabase GitHub OAuth token to call GitHub API
 */
export async function verifyGitHubPushAccess(repoUrl: string): Promise<GitHubPermissionCheck> {
    try {
        // Parse the repository URL
        const parsed = parseGitHubRepoUrl(repoUrl);
        if (!parsed) {
            return {
                hasAccess: false,
                error: 'Invalid GitHub repository URL. Please provide a valid GitHub URL (e.g., https://github.com/owner/repo)'
            };
        }
 
        const { owner, repo } = parsed;
 
        // Get GitHub access token from Supabase session
        const token = await getGitHubAccessToken();
        if (!token) {
            return {
                hasAccess: false,
                error: 'Not authenticated with GitHub. Please sign in with GitHub to verify repository access.'
            };
        }
 
        // Fetch repository information from GitHub API
        const repoResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}`, {
            headers: {
                'Authorization': `token ${token}`,
                'Accept': 'application/vnd.github.v3+json',
                'User-Agent': 'CollabAgent-VSCode'
            }
        });
 
        if (!repoResponse.ok) {
            if (repoResponse.status === 404) {
                return {
                    hasAccess: false,
                    error: `Repository not found: ${owner}/${repo}. Either the repository doesn't exist or you don't have access to it.`
                };
            } else if (repoResponse.status === 401) {
                return {
                    hasAccess: false,
                    error: 'GitHub authentication failed. Please try signing in again.'
                };
            }
            return {
                hasAccess: false,
                error: `Failed to access repository: ${repoResponse.statusText}`
            };
        }
 
        const repoData = await repoResponse.json();
 
        const repoInfo: GitHubRepoInfo = {
            owner: repoData.owner.login,
            repo: repoData.name,
            fullName: repoData.full_name,
            repoId: repoData.id,
            htmlUrl: repoData.html_url
        };
 
        // Check permissions
        // repoData.permissions: { admin: boolean, push: boolean, pull: boolean }
        const permissions = repoData.permissions;
 
        if (!permissions) {
            return {
                hasAccess: false,
                repoInfo,
                error: 'Unable to determine repository permissions. You may not have access to this repository.'
            };
        }
 
        // Determine permission level
        let permissionLevel: string;
        if (permissions.admin) {
            permissionLevel = 'admin';
        } else if (permissions.push) {
            permissionLevel = 'write';
        } else if (permissions.pull) {
            permissionLevel = 'read';
        } else {
            permissionLevel = 'none';
        }
 
        // User needs at least 'push' (write) access to create a team
        const hasRequiredAccess = permissions.admin || permissions.push;
 
        if (!hasRequiredAccess) {
            return {
                hasAccess: false,
                permission: permissionLevel,
                repoInfo,
                error: `Insufficient permissions for ${owner}/${repo}. You need push (write) or admin access to create a team with this repository.`
            };
        }
 
        return {
            hasAccess: true,
            permission: permissionLevel,
            repoInfo
        };
 
    } catch (error: any) {
        console.error('[GitHub Verification] Error:', error);
        return {
            hasAccess: false,
            error: `Verification failed: ${error.message || 'Unknown error'}`
        };
    }
}
 
/**
 * Gets the GitHub access token from VS Code global state or Supabase session
 */
async function getGitHubAccessToken(): Promise<string | null> {
    try {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { globalContext } = require('../extension');
 
        // Try to get cached token from global state first
        const cachedToken = globalContext?.globalState.get('github_access_token') as string | undefined;
        if (cachedToken) {
            console.log('[GitHub Verification] Using cached GitHub token');
            return cachedToken;
        }
 
        // Fallback: try to get from current Supabase session (only works immediately after OAuth)
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { getSupabase } = require('../auth/supabaseClient');
        const supabase = getSupabase();
 
        const { data: { session }, error } = await supabase.auth.getSession();
 
        if (error || !session) {
            console.log('[GitHub Verification] No active session');
            return null;
        }

        // GitHub OAuth provider tokens are stored in session.provider_token
        const githubToken = session.provider_token;

        if (githubToken) {
            // Cache it for future use
            console.log('[GitHub Verification] Found provider token, caching it');
            await globalContext?.globalState.update('github_access_token', githubToken);
            return githubToken;
        }

        console.log('[GitHub Verification] No GitHub provider token found in session');
        return null;
    } catch (error) {
        console.error('[GitHub Verification] Error getting GitHub token:', error);
        return null;
    }
}
 
/**
 * Stores the GitHub access token for future use
 * This should be called after successful GitHub OAuth
 */
export async function storeGitHubAccessToken(token: string): Promise<void> {
    try {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { globalContext } = require('../extension');
        await globalContext?.globalState.update('github_access_token', token);
        console.log('[GitHub Verification] GitHub token stored successfully');
    } catch (error) {
        console.error('[GitHub Verification] Error storing GitHub token:', error);
    }
}
 
/**
 * Clears the stored GitHub access token (on sign out)
 */
export async function clearGitHubAccessToken(): Promise<void> {
    try {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { globalContext } = require('../extension');
        await globalContext?.globalState.update('github_access_token', undefined);
        console.log('[GitHub Verification] GitHub token cleared');
    } catch (error) {
        console.error('[GitHub Verification] Error clearing GitHub token:', error);
    }
}
 
/**
 * Prompts user to verify their GitHub repository access
 * Shows clear error messages and guidance if verification fails
 */
export async function promptGitHubVerification(repoUrl: string): Promise<GitHubPermissionCheck> {
    // Show loading message
    return vscode.window.withProgress({
        location: vscode.ProgressLocation.Notification,
        title: 'Verifying GitHub repository access...',
        cancellable: false
    }, async () => {
        const result = await verifyGitHubPushAccess(repoUrl);
 
        if (result.hasAccess) {
            vscode.window.showInformationMessage(
                `✓ Verified: You have ${result.permission} access to ${result.repoInfo?.fullName}`
            );
        } else {
            vscode.window.showErrorMessage(
                `GitHub Verification Failed: ${result.error}`
            );
        }
 
        return result;
    });
}
 
/**
 * Checks if a repository URL is a GitHub repository
 */
export function isGitHubRepository(repoUrl: string | undefined): boolean {
    if (!repoUrl) return false;
    return repoUrl.includes('github.com');
}