import { supabase } from '../firebaseClient'; import type { GitHubConfig, GitHubOAuthStatus, GitHubUser, VerifyTokenResponse, InitRepoResponse, PushSolutionPayload, PushSolutionResponse, SyncAllResponse, } from '../types/githubTypes'; const STORAGE_KEYS = { TOKEN: 'algospaced_github_token', USERNAME: 'algospaced_github_username', REPO: 'algospaced_github_repo', BRANCH: 'algospaced_github_branch', AUTOCOMMIT: 'algospaced_github_autocommit', PRIVATE: 'algospaced_github_private', AVATAR: 'algospaced_github_avatar', NAME: 'algospaced_github_name', }; export function getGitHubConfig(): GitHubConfig { return { token: localStorage.getItem(STORAGE_KEYS.TOKEN) || '', username: localStorage.getItem(STORAGE_KEYS.USERNAME) || '', repoName: localStorage.getItem(STORAGE_KEYS.REPO) || 'algospaced-solutions', branch: localStorage.getItem(STORAGE_KEYS.BRANCH) || 'main', autoCommit: localStorage.getItem(STORAGE_KEYS.AUTOCOMMIT) !== 'false', isPrivate: localStorage.getItem(STORAGE_KEYS.PRIVATE) !== 'false', }; } export function getStoredGitHubUser(): GitHubUser | null { const login = localStorage.getItem(STORAGE_KEYS.USERNAME); if (!login) return null; return { login, name: localStorage.getItem(STORAGE_KEYS.NAME) || login, avatar_url: localStorage.getItem(STORAGE_KEYS.AVATAR) || '', html_url: `https://github.com/${login}`, }; } export function saveGitHubConfig(config: Partial, user?: GitHubUser): void { if (config.token !== undefined) localStorage.setItem(STORAGE_KEYS.TOKEN, config.token.trim()); if (config.username !== undefined) localStorage.setItem(STORAGE_KEYS.USERNAME, config.username.trim()); if (config.repoName !== undefined) localStorage.setItem(STORAGE_KEYS.REPO, config.repoName.trim()); if (config.branch !== undefined) localStorage.setItem(STORAGE_KEYS.BRANCH, config.branch.trim()); if (config.autoCommit !== undefined) localStorage.setItem(STORAGE_KEYS.AUTOCOMMIT, String(config.autoCommit)); if (config.isPrivate !== undefined) localStorage.setItem(STORAGE_KEYS.PRIVATE, String(config.isPrivate)); if (user) { if (user.login) localStorage.setItem(STORAGE_KEYS.USERNAME, user.login); if (user.name) localStorage.setItem(STORAGE_KEYS.NAME, user.name); if (user.avatar_url) localStorage.setItem(STORAGE_KEYS.AVATAR, user.avatar_url); } } export function clearGitHubConfig(): void { Object.values(STORAGE_KEYS).forEach((k) => localStorage.removeItem(k)); } /** * Checks if GitHub direct OAuth is configured in the backend environment. */ export async function getGitHubOAuthStatus(): Promise { try { const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/github/oauth/status`); if (!res.ok) return { configured: false, client_id: null }; return (await res.json()) as GitHubOAuthStatus; } catch { return { configured: false, client_id: null }; } } /** * 1-Click Native GitHub OAuth Connect. * Uses direct backend OAuth (/api/github/oauth/login & /callback) which works seamlessly for * all users (including guest and local sandbox modes) without requiring Firebase Console OAuth setup. */ export async function connectWithGitHubOAuth(): Promise<{ token: string; user: GitHubUser }> { const apiBase = import.meta.env.VITE_API_BASE_URL || ''; const loginUrl = `${apiBase}/api/github/oauth/login`; // Open popup immediately on user action to avoid browser popup blockers const popup = window.open( loginUrl, 'algospaced_github_oauth', 'width=600,height=750,menubar=no,toolbar=no,status=no,location=no' ); if (!popup) { throw new Error('Popup window was blocked by your browser. Please allow popups for AlgoSpaced and try again.'); } // Await postMessage from OAuth callback page const token = await new Promise((resolve, reject) => { let timer: ReturnType | null = null; const cleanup = () => { window.removeEventListener('message', handleMessage); if (timer !== null) { clearInterval(timer); timer = null; } }; const handleMessage = (event: MessageEvent) => { if (!event.data || typeof event.data !== 'object') return; const data = event.data as { type?: string; token?: string; error?: string }; if (data.type === 'GITHUB_OAUTH_SUCCESS') { cleanup(); if (data.token && typeof data.token === 'string') { resolve(data.token.trim()); } else { reject(new Error('GitHub authorization succeeded but no access token was returned.')); } } else if (data.type === 'GITHUB_OAUTH_ERROR') { cleanup(); reject(new Error(data.error || 'GitHub authorization was denied or encountered an error.')); } }; window.addEventListener('message', handleMessage); // Detect if user closes popup before authorization finishes timer = setInterval(() => { if (popup.closed) { cleanup(); reject(new Error('GitHub authorization window was closed before completing.')); } }, 1000); }); // Verify token with backend to fetch user profile info const verifyRes = await verifyGitHubToken(token); if (!verifyRes.valid || !verifyRes.user) { throw new Error(verifyRes.error || 'Failed to retrieve profile with GitHub token.'); } const user = verifyRes.user; saveGitHubConfig( { token, username: user.login, repoName: getGitHubConfig().repoName || 'algospaced-solutions', }, user ); return { token, user }; } /** * Verifies a token with the backend and returns user metadata. */ export async function verifyGitHubToken(token: string): Promise { const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/github/verify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: token.trim() }), }); if (!res.ok) { const errData = await res.json().catch(() => ({})); return { valid: false, error: errData.detail || `Server returned error (${res.status})`, }; } return (await res.json()) as VerifyTokenResponse; } /** * Ensures repository exists or creates a new one. */ export async function initGitHubRepo( token: string, repoName: string, isPrivate: boolean = true ): Promise { const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/github/init-repo`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: token.trim(), repo_name: repoName.trim(), private: isPrivate, }), }); if (!res.ok) { const errData = await res.json().catch(() => ({})); throw new Error(errData.detail || `Failed to initialize repository (${res.status})`); } return (await res.json()) as InitRepoResponse; } /** * Commits a single solution code file and markdown spec to GitHub. */ export async function pushSolutionToGitHub( payload: PushSolutionPayload ): Promise { const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/github/push-solution`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); if (!res.ok) { const errData = await res.json().catch(() => ({})); throw new Error(errData.detail || `Failed to commit solution (${res.status})`); } return (await res.json()) as PushSolutionResponse; } /** * Batch-synchronizes all library problems to the repository. */ export async function syncAllSolutionsToGitHub( token: string, repo: string, branch: string = 'main' ): Promise { const { data: { session } } = await supabase.auth.getSession(); const authHeader = session ? `Bearer ${session.access_token}` : 'Bearer sandbox'; const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/github/sync-all`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': authHeader, }, body: JSON.stringify({ token: token.trim(), repo: repo.trim(), branch: branch.trim(), }), }); if (!res.ok) { const errData = await res.json().catch(() => ({})); throw new Error(errData.detail || `Sync failed (${res.status})`); } return (await res.json()) as SyncAllResponse; }