From 6bd5debb7f4c88f748cf79febe025f783c2e05a1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 25 Aug 2025 14:41:14 -0500 Subject: [PATCH] Clone by Nostr URI --- src/pages/Clone.tsx | 214 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 196 insertions(+), 18 deletions(-) diff --git a/src/pages/Clone.tsx b/src/pages/Clone.tsx index 51184b41..0dc685dd 100644 --- a/src/pages/Clone.tsx +++ b/src/pages/Clone.tsx @@ -8,9 +8,18 @@ import { Label } from '@/components/ui/label'; import { GitBranch, Loader2, AlertCircle } from 'lucide-react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; +import { useNostr } from '@nostrify/react'; +import { nip19 } from 'nostr-tools'; +import type { Project } from '@/lib/ProjectsManager'; import { useSeoMeta } from '@unhead/react'; +interface NostrCloneUri { + pubkey: string; + dTag: string; + relay?: string; +} + export default function Clone() { const [repoUrl, setRepoUrl] = useState(''); const [isCloning, setIsCloning] = useState(false); @@ -18,6 +27,7 @@ export default function Clone() { const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { toast } = useToast(); + const { nostr } = useNostr(); useSeoMeta({ title: 'Import Repository - Shakespeare', @@ -44,9 +54,69 @@ export default function Clone() { } }; + const parseNostrCloneUri = (uri: string): NostrCloneUri | null => { + try { + if (!uri.startsWith('nostr://')) { + return null; + } + + const path = uri.slice(8); // Remove 'nostr://' prefix + const parts = path.split('/'); + + if (parts.length < 2) { + return null; + } + + const npubOrPubkey = parts[0]; + let pubkey: string; + + // Try to decode as npub first, otherwise assume it's already a hex pubkey + try { + const decoded = nip19.decode(npubOrPubkey); + if (decoded.type === 'npub') { + pubkey = decoded.data; + } else { + return null; + } + } catch { + // If decoding fails, check if it's a valid hex pubkey + if (/^[a-f0-9]{64}$/i.test(npubOrPubkey)) { + pubkey = npubOrPubkey; + } else { + return null; + } + } + + // Check if we have relay and d-tag or just d-tag + if (parts.length === 3) { + // Format: nostr://npub/relay/dtag + return { + pubkey, + relay: parts[1], + dTag: parts[2], + }; + } else if (parts.length === 2) { + // Format: nostr://npub/dtag + return { + pubkey, + dTag: parts[1], + }; + } + + return null; + } catch { + return null; + } + }; + const validateGitUrl = (url: string): boolean => { if (!url.trim()) return false; + // Check if it's a Nostr clone URI + if (url.startsWith('nostr://')) { + return parseNostrCloneUri(url) !== null; + } + // Basic URL validation try { new URL(url); @@ -59,6 +129,73 @@ export default function Clone() { return gitUrlPattern.test(url) || url.includes('github.com') || url.includes('gitlab.com'); }; + const fetchNostrRepository = async (nostrUri: NostrCloneUri): Promise => { + const signal = AbortSignal.timeout(10000); // 10 second timeout + + // Build the filter for the NIP-34 repository announcement + const filter = { + kinds: [30617], + authors: [nostrUri.pubkey], + '#d': [nostrUri.dTag], + limit: 1, + }; + + // Use a specific relay if provided + const client = nostrUri.relay + ? nostr.relay(nostrUri.relay) + : nostr; + + // Query for the repository announcement event + const events = await client.query([filter], { signal }); + + if (events.length === 0) { + throw new Error('Repository not found on Nostr network'); + } + + const repoEvent = events[0]; + + // Extract clone URLs from the event tags + const cloneUrls: string[] = []; + for (const tag of repoEvent.tags) { + if (tag[0] === 'clone' && tag[1]) { + cloneUrls.push(tag[1]); + } + } + + if (cloneUrls.length === 0) { + throw new Error('No clone URLs found in repository announcement'); + } + + return cloneUrls; + }; + + const tryCloneUrls = async (cloneUrls: string[], repoName: string): Promise => { + let lastError: Error | null = null; + + for (const cloneUrl of cloneUrls) { + try { + console.log(`Attempting to clone from: ${cloneUrl}`); + + // Try cloning with a timeout + const project = await Promise.race([ + projectsManager.cloneProject(repoName, cloneUrl), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Clone timeout')), 30000) + ) + ]); + + return project; // Success! + } catch (error) { + console.warn(`Failed to clone from ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + continue; // Try the next URL + } + } + + // If we get here, all clone attempts failed + throw lastError || new Error('All clone attempts failed'); + }; + const handleClone = async () => { if (!repoUrl.trim()) { setError('Please enter a repository URL'); @@ -66,7 +203,7 @@ export default function Clone() { } if (!validateGitUrl(repoUrl)) { - setError('Please enter a valid Git repository URL (e.g., https://github.com/user/repo.git)'); + setError('Please enter a valid Git repository URL or Nostr clone URI (e.g., nostr://npub.../repo-name)'); return; } @@ -74,26 +211,57 @@ export default function Clone() { setError(null); try { - // Extract repository name from URL - const repoName = extractRepoName(repoUrl); - - // Clone the repository using ProjectsManager await projectsManager.init(); - const project = await projectsManager.cloneProject(repoName, repoUrl.trim()); - toast({ - title: "Repository imported successfully", - description: `"${repoName}" has been cloned and is ready for development.`, - }); + // Check if it's a Nostr clone URI + const nostrUri = parseNostrCloneUri(repoUrl.trim()); - // Navigate to the new project - navigate(`/project/${project.id}`); + if (nostrUri) { + // Handle Nostr clone URI + console.log('Parsing Nostr clone URI:', nostrUri); + + // Fetch the repository announcement from Nostr + const cloneUrls = await fetchNostrRepository(nostrUri); + console.log('Found clone URLs:', cloneUrls); + + // Extract repository name from d-tag + const repoName = nostrUri.dTag; + + // Try cloning from each URL in order + const project = await tryCloneUrls(cloneUrls, repoName); + + toast({ + title: "Nostr repository imported successfully", + description: `"${repoName}" has been cloned from Nostr and is ready for development.`, + }); + + // Navigate to the new project + navigate(`/project/${project.id}`); + } else { + // Handle regular Git URL + const repoName = extractRepoName(repoUrl); + const project = await projectsManager.cloneProject(repoName, repoUrl.trim()); + + toast({ + title: "Repository imported successfully", + description: `"${repoName}" has been cloned and is ready for development.`, + }); + + // Navigate to the new project + navigate(`/project/${project.id}`); + } } catch (error) { console.error('Failed to clone repository:', error); let errorMessage = 'Failed to clone repository'; if (error instanceof Error) { - if (error.message.includes('404') || error.message.includes('not found')) { + if (error.message.includes('Repository not found on Nostr network')) { + errorMessage = 'Repository not found on Nostr network. Please check the URI and try again.'; + } else if (error.message.includes('No clone URLs found')) { + errorMessage = 'Repository announcement found but no clone URLs available.'; + } else if (error.message.includes('All clone attempts failed')) { + errorMessage = 'Repository found but all clone URLs failed. The repository may be unavailable.'; + } else if (error.message.includes('404') || error.message.includes('not found')) { errorMessage = 'Repository not found. Please check the URL and try again.'; } else if (error.message.includes('403') || error.message.includes('forbidden')) { errorMessage = 'Access denied. The repository may be private or require authentication.'; @@ -141,16 +309,16 @@ export default function Clone() { Repository URL - Enter the HTTPS URL of the Git repository you want to import + Enter a Git repository URL or Nostr clone URI to import
- + { setRepoUrl(e.target.value); @@ -161,7 +329,7 @@ export default function Clone() { className="text-base" />

- Supports GitHub, GitLab, and other Git hosting services + Supports Git URLs and Nostr clone URIs (nostr://npub.../repo-name)

@@ -197,7 +365,17 @@ export default function Clone() {
  • • Public GitHub repositories
  • • Public GitLab repositories
  • • Any public Git repository accessible via HTTPS
  • +
  • • Nostr repositories via NIP-34 clone URIs
  • +
    +

    + Nostr Clone URI Examples: +

    +
      +
    • • nostr://npub1.../repo-name
    • +
    • • nostr://npub1.../relay.example.com/repo-name
    • +
    +

    Note: Private repositories requiring authentication are not currently supported.