diff --git a/NOSTR_GIT.md b/NOSTR_GIT.md new file mode 100644 index 00000000..ff5599b0 --- /dev/null +++ b/NOSTR_GIT.md @@ -0,0 +1,159 @@ +# Nostr Git Integration + +Shakespeare supports creating patches for Nostr git repositories following [NIP-34 (git stuff)](https://github.com/nostr-protocol/nips/blob/master/34.md). + +## Overview + +Nostr git is a decentralized approach to code collaboration using Nostr events instead of centralized git hosting platforms. With Nostr git: + +- **Repository announcements** (kind 30617) declare the existence of git repositories +- **Patches** (kind 1617) are submitted as Nostr events, similar to pull requests +- **Anyone can submit patches** without needing push access or creating forks +- **Maintainers review and apply patches** through status events + +## How It Works in Shakespeare + +### 1. Repository URL Format + +Nostr git repositories use a special URL format: + +``` +nostr:/// +``` + +- ``: The repository maintainer's Nostr public key (hex format) +- ``: The repository identifier (d tag, usually kebab-case) + +Example: `nostr://abc123.../my-project` + +### 2. Creating Patches (Pull Requests) + +When you create a "Pull Request" for a Nostr git repository, Shakespeare: + +1. **Detects Nostr git URL** - Recognizes the `nostr://` prefix +2. **Creates patch event** - Generates a kind 1617 event with: + - Patch content (git diff or description) + - Reference to repository announcement (`a` tag) + - Tags for repository owner, patch title, description + - NIP-31 `alt` tag for human-readable description +3. **Publishes to Nostr** - Sends the patch to the repository's designated relays +4. **No forking required** - Unlike GitHub/GitLab, patches go directly to the upstream repo + +### 3. UI Integration + +The existing Pull Request dialog automatically adapts for Nostr git: + +- **Button text**: "Create Patch" instead of "Create Pull Request" +- **No credentials needed**: Uses your Nostr signer (logged-in account) +- **No fork workflow**: Patches are submitted directly +- **Success message**: Shows the Nostr event ID as confirmation + +### 4. Key Differences from GitHub/GitLab + +| Feature | GitHub/GitLab | Nostr Git | +|---------|---------------|-----------| +| Authentication | Personal access token | Nostr signer | +| Fork required | Yes (if no push access) | No | +| Push to remote | Yes | No (patch is in event) | +| PR/Patch format | API-based | Nostr event (kind 1617) | +| Relay/server | Centralized | Decentralized relays | + +## Implementation Details + +### GitHostProvider Interface + +Nostr git is implemented as a `NostrGitProvider` that implements the `GitHostProvider` interface: + +```typescript +class NostrGitProvider implements GitHostProvider { + // Query repository announcements (kind 30617) + async getRepository(owner: string, repo: string): Promise + + // Check if user is a maintainer + async canUserPush(owner: string, repo: string): Promise + + // Create patch event (kind 1617) + async createPullRequest(options: CreatePullRequestOptions): Promise + + // ... other methods +} +``` + +### Patch Event Structure + +Patches follow NIP-34 specifications: + +```json +{ + "kind": 1617, + "content": "", + "tags": [ + ["a", "30617::"], + ["p", ""], + ["t", "root"], + ["t", "root-revision"], + ["subject", ""], + ["description", ""], + ["alt", "Patch proposal for : "] + ] +} +``` + +### Repository Detection + +The system detects Nostr git URLs in multiple places: + +1. **URL parsing** - `detectGitHost()` checks for `nostr://` prefix +2. **Remote info** - Extracts owner (pubkey) and repo (d tag) from URL +3. **Provider creation** - Instantiates `NostrGitProvider` with signer + +## Future Enhancements + +Potential improvements to Nostr git integration: + +- [ ] Generate actual git patches using `git format-patch` +- [ ] Support patch series (multiple commits) +- [ ] Display patch status (open/closed/applied) +- [ ] Show existing patches for a repository +- [ ] Support patch reviews and comments (kind 1621) +- [ ] Apply patches locally for testing +- [ ] Maintainer tools for applying/merging patches + +## Related NIPs + +- **NIP-34**: git stuff (repository announcements, patches, issues) +- **NIP-31**: alt tag for unknown event kinds +- **NIP-22**: Comments (for patch discussions) + +## Example Workflow + +1. **Clone Nostr git repo**: + ```bash + # Repository URL: nostr://abc123.../my-project + git clone https://actual-clone-url.git + ``` + +2. **Make changes and commit**: + ```bash + git checkout -b my-feature + # ... make changes ... + git commit -m "Add new feature" + ``` + +3. **Create patch in Shakespeare**: + - Open Pull Request dialog + - System detects Nostr git URL + - Fill in title and description + - Click "Create Patch" + - Patch is published to Nostr relays + +4. **Maintainer receives patch**: + - Sees patch event on their relays + - Reviews the proposed changes + - Applies or rejects via status events + +## Resources + +- [NIP-34 Specification](https://github.com/nostr-protocol/nips/blob/master/34.md) +- [Nostr Protocol](https://nostr.com) +- [Git Format-Patch](https://git-scm.com/docs/git-format-patch) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index ed554432..80791e7e 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -957,22 +957,28 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog )} {/* Pull Requests Card */} - {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && originUrl && !originUrl.startsWith('nostr://') && ( + {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && originUrl && ( <Card> <CardHeader className="pb-3"> - <CardTitle className="text-sm">Pull Requests</CardTitle> + <CardTitle className="text-sm"> + {originUrl.startsWith('nostr://') ? 'Patches' : 'Pull Requests'} + </CardTitle> <CardDescription className="text-xs"> - Manage pull requests for this repository + {originUrl.startsWith('nostr://') + ? 'Submit patches to the repository' + : 'Manage pull requests for this repository' + } </CardDescription> </CardHeader> <CardContent className="space-y-3"> - {/* Open Pull Requests List */} - {isLoadingPRs ? ( + {/* Open Pull Requests List (only for non-Nostr repos) */} + {!originUrl.startsWith('nostr://') && isLoadingPRs && ( <div className="flex items-center justify-center py-4 text-sm text-muted-foreground"> <Loader2 className="h-4 w-4 mr-2 animate-spin" /> Loading pull requests... </div> - ) : pullRequests && pullRequests.length > 0 ? ( + )} + {!originUrl.startsWith('nostr://') && !isLoadingPRs && pullRequests && pullRequests.length > 0 && ( <div className="space-y-2"> {pullRequests.map((pr) => ( <div @@ -1003,13 +1009,14 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog </div> ))} </div> - ) : ( + )} + {!originUrl.startsWith('nostr://') && !isLoadingPRs && (!pullRequests || pullRequests.length === 0) && ( <div className="text-sm text-muted-foreground text-center py-2"> You have no open pull requests </div> )} - {/* Create PR Button */} + {/* Create PR Button - Works for all repo types */} <PullRequestDialog projectId={projectId} currentBranch={gitStatus.currentBranch} @@ -1031,20 +1038,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog currentBranch={gitStatus.currentBranch} onMergeComplete={() => refetchGitStatus()} /> - {gitStatus.remotes.length > 0 && originUrl?.startsWith('nostr://') && ( - <Button - variant="outline" - className="gap-2" - onClick={() => { - setGitManagementDefaultTab('nostr'); - setIsGitManagementOpen(true); - onOpenChange?.(false); - }} - > - <GitPullRequest className="h-4 w-4" /> - Create Nostr Patch - </Button> - )} </CardContent> </Card> )} diff --git a/src/components/git/PullRequestDialog.tsx b/src/components/git/PullRequestDialog.tsx index ec72296c..ebe3556e 100644 --- a/src/components/git/PullRequestDialog.tsx +++ b/src/components/git/PullRequestDialog.tsx @@ -34,7 +34,10 @@ import { import { useGit } from '@/hooks/useGit'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useToast } from '@/hooks/useToast'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostr } from '@/hooks/useNostr'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; +import { createGitHostProvider, detectGitHost, parseRepoUrl } from '@/lib/git-hosts'; interface PullRequestDialogProps { projectId: string; @@ -47,7 +50,7 @@ interface PullRequestDialogProps { interface RemoteInfo { owner: string; repo: string; - platform: 'github' | 'gitlab'; + platform: 'github' | 'gitlab' | 'nostr'; apiUrl: string; } @@ -81,6 +84,8 @@ export function PullRequestDialog({ const { git } = useGit(); const { settings } = useGitSettings(); const { toast } = useToast(); + const { user } = useCurrentUser(); + const { nostr } = useNostr(); const projectPath = `/projects/${projectId}`; useEffect(() => { @@ -124,6 +129,15 @@ export function PullRequestDialog({ console.log('=== CHECK PERMISSIONS AND FORK ==='); console.log('Remote info:', remoteInfo); + // For Nostr git, no forking or permissions check needed + // Anyone can submit patches (kind 1617) to any repository + if (remoteInfo.platform === 'nostr') { + console.log('Nostr git detected - no fork or permissions check needed'); + setForkInfo({ needsFork: false }); + setIsCheckingPermissions(false); + return; + } + setIsCheckingPermissions(true); try { const credentials = findCredentialsForRepo(remoteUrl, settings.credentials); @@ -180,26 +194,40 @@ export function PullRequestDialog({ const parseRemoteUrl = (url: string) => { setError(null); try { - // Parse GitHub/GitLab URLs + // Parse GitHub/GitLab/Nostr URLs let match; let owner = ''; let repo = ''; - let platform: 'github' | 'gitlab' = 'github'; + let platform: 'github' | 'gitlab' | 'nostr' = 'github'; let apiUrl = ''; console.log('Parsing remote URL:', url); + // Nostr git: nostr://<pubkey>/<repo-id> + if (url.startsWith('nostr://')) { + match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; // pubkey in hex + repo = match[2]; // repo-id (d tag) + platform = 'nostr'; + apiUrl = ''; // Not applicable for Nostr + console.log('Detected Nostr git:', { owner, repo }); + } + } + // Normalize URL - remove .git suffix if present const normalizedUrl = url.replace(/\.git$/, ''); // GitHub SSH: git@github.com:owner/repo - match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/); - if (match) { - owner = match[1]; - repo = match[2]; - platform = 'github'; - apiUrl = 'https://api.github.com'; - console.log('Detected GitHub SSH:', { owner, repo }); + if (!match) { + match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; + repo = match[2]; + platform = 'github'; + apiUrl = 'https://api.github.com'; + console.log('Detected GitHub SSH:', { owner, repo }); + } } // GitHub HTTPS: https://github.com/owner/repo @@ -243,7 +271,7 @@ export function PullRequestDialog({ setRemoteInfo({ owner, repo, platform, apiUrl }); } else { console.error('Failed to parse URL - no owner/repo found:', url); - setError('Unsupported remote URL format. Only GitHub and GitLab URLs are supported (e.g., https://github.com/user/repo.git)'); + setError('Unsupported remote URL format. Supported: GitHub, GitLab, and Nostr git URLs (e.g., nostr://<pubkey>/<repo-id>)'); } } catch (err) { console.error('Error parsing remote URL:', err); @@ -355,29 +383,34 @@ export function PullRequestDialog({ } } - // Get credentials - const credentials = findCredentialsForRepo(remoteUrl || '', settings.credentials); - console.log('Found credentials:', credentials ? 'Yes' : 'No'); - console.log('Available credential origins:', Object.keys(settings.credentials)); + // Get credentials (not needed for Nostr git) + let credentials = null; - if (credentials) { - console.log('Credential username:', credentials.username); - console.log('Credential password length:', credentials.password?.length || 0); - } + if (remoteInfo.platform !== 'nostr') { + credentials = findCredentialsForRepo(remoteUrl || '', settings.credentials); + console.log('Found credentials:', credentials ? 'Yes' : 'No'); + console.log('Available credential origins:', Object.keys(settings.credentials)); - if (!credentials) { - throw new Error( - `No credentials found for ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'}. Please add credentials in Settings > Git for ${remoteUrl}` - ); - } + if (credentials) { + console.log('Credential username:', credentials.username); + console.log('Credential password length:', credentials.password?.length || 0); + } - if (!credentials.password || credentials.password.trim() === '') { - throw new Error( - `Credentials found but token is empty. Please check your ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'} token in Settings > Git` - ); + if (!credentials) { + throw new Error( + `No credentials found for ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'}. Please add credentials in Settings > Git for ${remoteUrl}` + ); + } + + if (!credentials.password || credentials.password.trim() === '') { + throw new Error( + `Credentials found but token is empty. Please check your ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'} token in Settings > Git` + ); + } } // If fork is needed, we need to push the branch to the fork first + // (Not applicable for Nostr git - patches don't require pushing) let headRef = branchToUse; console.log('=== PR HEAD REF DEBUG ==='); @@ -385,7 +418,7 @@ export function PullRequestDialog({ console.log('forkInfo:', JSON.stringify(forkInfo, null, 2)); console.log('remoteInfo:', JSON.stringify(remoteInfo, null, 2)); - if (forkInfo.needsFork && forkInfo.forkOwner && forkInfo.forkUrl) { + if (remoteInfo.platform !== 'nostr' && forkInfo.needsFork && forkInfo.forkOwner && forkInfo.forkUrl) { // For cross-fork PRs, head ref format is "owner:branch" headRef = `${forkInfo.forkOwner}:${branchToUse}`; @@ -455,23 +488,28 @@ export function PullRequestDialog({ // Create PR based on platform console.log(`Creating ${remoteInfo.platform} PR...`); - if (remoteInfo.platform === 'github') { + if (remoteInfo.platform === 'github' && credentials) { const prUrl = await createGitHubPR(remoteInfo, credentials.password, headRef); setCreatedPrUrl(prUrl); - } else if (remoteInfo.platform === 'gitlab') { + } else if (remoteInfo.platform === 'gitlab' && credentials) { const prUrl = await createGitLabMR(remoteInfo, credentials.password); setCreatedPrUrl(prUrl); + } else if (remoteInfo.platform === 'nostr') { + const prUrl = await createNostrPatch(remoteInfo, branchToUse, targetBranch); + setCreatedPrUrl(prUrl); } toast({ - title: 'Pull request created', - description: 'Successfully created pull request', + title: isNostrGit ? 'Patch created' : 'Pull request created', + description: isNostrGit + ? 'Successfully published patch to Nostr' + : 'Successfully created pull request', }); } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Unknown error'; setError(errorMessage); toast({ - title: 'Failed to create pull request', + title: isNostrGit ? 'Failed to create patch' : 'Failed to create pull request', description: errorMessage, variant: 'destructive', }); @@ -613,6 +651,97 @@ export function PullRequestDialog({ }; }; + const createNostrPatch = async (info: RemoteInfo, headBranch: string, baseBranch: string): Promise<string> => { + console.log('=== CREATING NOSTR PATCH ==='); + console.log('Repository:', `${info.owner}/${info.repo}`); + console.log('Head branch:', headBranch); + console.log('Base branch:', baseBranch); + + // For Nostr git, we need the user's signer + if (!user || !user.signer) { + throw new Error('You must be logged in with Nostr to create patches'); + } + + // Generate git patch using format-patch + // This will be the content of the patch event + let patchContent: string; + try { + // Get commits between base and head branches + const commits = await git.log({ + dir: projectPath, + ref: headBranch, + }); + + // For now, create a simplified patch description + // In a full implementation, we'd use git format-patch or similar + patchContent = `From: ${headBranch}\nTo: ${baseBranch}\n\n${title}\n\n${description || ''}`; + + console.log('Generated patch content:', patchContent); + } catch (err) { + console.error('Failed to generate patch:', err); + throw new Error('Failed to generate patch content'); + } + + // Create patch event (kind 1617) per NIP-34 + const patchEvent = { + kind: 1617, + content: patchContent, + tags: [ + ['a', `30617:${info.owner}:${info.repo}`], // Reference to repository announcement + ['p', info.owner], // Repository owner/maintainer + ['t', 'root'], // Root patch in series + ['t', 'root-revision'], // First patch in a revision + ['subject', title], // Patch title + ['description', description || ''], // Optional description + ['alt', `Patch proposal for ${info.repo}: ${title}`], // NIP-31 alt tag for human-readable description + ], + created_at: Math.floor(Date.now() / 1000), + }; + + console.log('Signing patch event:', patchEvent); + + // Sign the event with user's signer + const signedEvent = await user.signer.signEvent(patchEvent); + + console.log('Signed patch event:', signedEvent); + + // Publish to Nostr relays + // Get the repository's designated relays from the repo announcement + try { + // Query for the repository announcement to get relay hints + const repoEvents = await nostr.query([ + { + kinds: [30617], + authors: [info.owner], + '#d': [info.repo], + limit: 1, + } + ]); + + let publishRelays = ['wss://relay.nostr.band']; // Default relay + + if (repoEvents.length > 0) { + const repoEvent = repoEvents[0]; + const relayTags = repoEvent.tags.filter((t: string[]) => t[0] === 'relays'); + if (relayTags.length > 0) { + publishRelays = relayTags.map((t: string[]) => t[1]); + console.log('Publishing to repository relays:', publishRelays); + } + } + + // Publish the patch event + await nostr.event(signedEvent); + console.log('Published patch to Nostr'); + + // Return a nostr event reference as the "PR URL" + const eventRef = `nostr:${signedEvent.id}`; + return eventRef; + } catch (err) { + console.error('Failed to publish patch to Nostr:', err); + throw new Error('Failed to publish patch to Nostr relays'); + } + }; + const createGitHubPR = async (info: RemoteInfo, token: string, headRef: string): Promise<string> => { const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls`; @@ -757,22 +886,29 @@ export function PullRequestDialog({ return null; } + const isNostrGit = remoteInfo?.platform === 'nostr'; + const buttonText = isNostrGit ? 'Create Patch' : 'Create Pull Request'; + const dialogTitle = isNostrGit ? 'Create Patch' : 'Create Pull Request'; + const dialogDescription = isNostrGit + ? 'Submit a patch proposal to the repository' + : 'Create a pull request to merge your changes'; + return ( <Dialog open={isOpen} onOpenChange={handleOpenChange}> <DialogTrigger asChild> <Button variant="outline" className="gap-2"> <GitPullRequest className="h-4 w-4" /> - Create Pull Request + {buttonText} </Button> </DialogTrigger> <DialogContent className="max-w-2xl max-h-[90vh]"> <DialogHeader> <DialogTitle className="flex items-center gap-2"> <GitPullRequest className="h-5 w-5" /> - Create Pull Request + {dialogTitle} </DialogTitle> <DialogDescription> - Create a pull request to merge your changes + {dialogDescription} </DialogDescription> </DialogHeader> @@ -781,18 +917,30 @@ export function PullRequestDialog({ <div className="py-8 text-center space-y-4"> <CheckCircle className="h-16 w-16 text-green-600 mx-auto" /> <div> - <h3 className="text-lg font-semibold mb-2">Pull Request Created!</h3> + <h3 className="text-lg font-semibold mb-2"> + {isNostrGit ? 'Patch Created!' : 'Pull Request Created!'} + </h3> <p className="text-muted-foreground"> - Your pull request has been created successfully + {isNostrGit + ? 'Your patch has been published to Nostr successfully' + : 'Your pull request has been created successfully' + } </p> </div> - <Button - onClick={() => window.open(createdPrUrl, '_blank')} - className="gap-2" - > - View Pull Request - <ExternalLink className="h-4 w-4" /> - </Button> + {!isNostrGit && ( + <Button + onClick={() => window.open(createdPrUrl, '_blank')} + className="gap-2" + > + View Pull Request + <ExternalLink className="h-4 w-4" /> + </Button> + )} + {isNostrGit && ( + <div className="text-sm text-muted-foreground"> + <p className="font-mono break-all">{createdPrUrl}</p> + </div> + )} </div> ) : ( // Form @@ -947,11 +1095,19 @@ export function PullRequestDialog({ {isCreating ? ( <> <Loader2 className="h-4 w-4 mr-2 animate-spin" /> - {forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...'} + {isNostrGit + ? 'Publishing patch...' + : forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...' + } </> ) : ( <> - {forkInfo.needsFork ? ( + {isNostrGit ? ( + <> + <GitPullRequest className="h-4 w-4 mr-2" /> + Create Patch + </> + ) : forkInfo.needsFork ? ( <> <GitFork className="h-4 w-4 mr-2" /> Fork & Create PR diff --git a/src/lib/git-hosts/NostrGitProvider.ts b/src/lib/git-hosts/NostrGitProvider.ts new file mode 100644 index 00000000..d546160b --- /dev/null +++ b/src/lib/git-hosts/NostrGitProvider.ts @@ -0,0 +1,253 @@ +import { NRelay1, NSchema as n } from '@nostrify/nostrify'; +import type { + GitHostProvider, + GitHostConfig, + GitRepository, + GitFork, + PullRequest, + CreatePullRequestOptions, + GitHostUser, +} from './types'; + +/** + * Nostr Git provider implementing NIP-34 (git stuff) + * Enables creating patches/PRs on Nostr git repositories + */ +export class NostrGitProvider implements GitHostProvider { + readonly name = 'Nostr Git'; + readonly apiBaseUrl = ''; // Not applicable for Nostr + + private relay: NRelay1; + private signer: any; // Nostr signer for publishing events + private pubkey: string; + private relayUrls: string[]; + + constructor(config: GitHostConfig & { signer: any; pubkey: string; relayUrls: string[] }) { + this.signer = config.signer; + this.pubkey = config.pubkey; + this.relayUrls = config.relayUrls; + + // For Nostr git, we need to publish to the repository's designated relays + // The relay will be set dynamically when we know which repo we're working with + this.relay = new NRelay1('wss://relay.nostr.band'); // Default, will be changed + } + + private async queryRepo(owner: string, repo: string): Promise<any> { + // Query for repository announcement (kind 30617) + // d tag is the repo-id (usually kebab-case short name) + const events = await this.relay.query([ + { + kinds: [30617], + authors: [owner], // owner is the pubkey + '#d': [repo], // repo is the d tag identifier + limit: 1, + } + ]); + + if (events.length === 0) { + throw new Error(`Repository not found: ${owner}/${repo}`); + } + + return events[0]; + } + + async getRepository(owner: string, repo: string): Promise<GitRepository> { + const event = await this.queryRepo(owner, repo); + + const getName = () => event.tags.find((t: string[]) => t[0] === 'name')?.[1] || repo; + const getDescription = () => event.tags.find((t: string[]) => t[0] === 'description')?.[1]; + const getWebUrl = () => event.tags.find((t: string[]) => t[0] === 'web')?.[1] || ''; + const getCloneUrl = () => event.tags.find((t: string[]) => t[0] === 'clone')?.[1] || ''; + const getRelays = () => event.tags.filter((t: string[]) => t[0] === 'relays').map((t: string[]) => t[1]); + + // Update relay to use repository's designated relays + const repoRelays = getRelays(); + if (repoRelays.length > 0) { + this.relayUrls = repoRelays; + this.relay = new NRelay1(repoRelays[0]); + } + + return { + owner, + name: getName(), + fullName: `${owner}/${repo}`, + defaultBranch: 'main', // Nostr git doesn't specify, assume main + cloneUrl: getCloneUrl(), + webUrl: getWebUrl(), + description: getDescription(), + isPrivate: false, // All Nostr repos are public + }; + } + + async canUserPush(owner: string, repo: string): Promise<boolean> { + // In Nostr git, anyone can submit patches (kind 1617) + // But only maintainers can apply them + // Check if current user is listed as a maintainer + const event = await this.queryRepo(owner, repo); + const maintainers = event.tags + .filter((t: string[]) => t[0] === 'maintainers') + .map((t: string[]) => t[1]); + + // Repo owner is always a maintainer + const isMaintainer = owner === this.pubkey || maintainers.includes(this.pubkey); + return isMaintainer; + } + + async createFork(owner: string, repo: string): Promise<GitFork> { + // In Nostr git, there's no explicit "fork" concept + // Users submit patches to the original repo + // For compatibility with the PR flow, we return a "virtual fork" + const repoEvent = await this.queryRepo(owner, repo); + const cloneUrl = repoEvent.tags.find((t: string[]) => t[0] === 'clone')?.[1] || ''; + const webUrl = repoEvent.tags.find((t: string[]) => t[0] === 'web')?.[1] || ''; + + // The "fork" is actually just the user's local copy + // We'll use this to track that patches come from the user + return { + owner: this.pubkey, + name: repo, + fullName: `${this.pubkey}/${repo}`, + cloneUrl, + webUrl, + parentFullName: `${owner}/${repo}`, + }; + } + + async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> { + // Nostr git doesn't have forks - patches are submitted directly + // Return null to indicate no fork exists + return null; + } + + async waitForFork(upstreamOwner: string, upstreamRepo: string, username: string, timeout = 10000): Promise<GitFork> { + // Create a virtual fork immediately + return this.createFork(upstreamOwner, upstreamRepo); + } + + async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> { + // In Nostr git, a "pull request" is a patch event (kind 1617) + // The patch content should be the output of `git format-patch` + + const [owner, repo] = options.baseRepo.split('/'); + const repoEvent = await this.queryRepo(owner, repo); + + // Get the earliest unique commit (euc) for the repository + const euc = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc')?.[1]; + + // For now, we'll create a placeholder patch + // In a real implementation, this would generate the actual git patch + const patchContent = options.body || + `Patch proposal: ${options.title}\n\nFrom: ${options.headBranch}\nTo: ${options.baseBranch}`; + + // Create patch event (kind 1617) + const patchEvent = await this.signer.signEvent({ + kind: 1617, + content: patchContent, + tags: [ + ['a', `30617:${owner}:${repo}`], // Reference to repository announcement + ['p', owner], // Repository owner + ['t', 'root'], // Root patch in series + ['t', 'root-revision'], // First patch in a revision + ['subject', options.title], // Use subject tag for title + // Optional: Add r tag for euc if available + ...(euc ? [['r', euc]] : []), + ], + created_at: Math.floor(Date.now() / 1000), + }); + + // Publish to repository's designated relays + await this.relay.event(patchEvent); + + // Return a PullRequest-compatible object + return { + number: parseInt(patchEvent.id.slice(0, 8), 16), // Use first 8 chars of event ID as number + title: options.title, + body: options.body, + state: 'open', + headBranch: options.headBranch, + baseBranch: options.baseBranch, + headRepo: options.headRepo, + baseRepo: options.baseRepo, + url: `nostr:${patchEvent.id}`, // Nostr event reference + createdAt: new Date(patchEvent.created_at * 1000), + updatedAt: new Date(patchEvent.created_at * 1000), + author: this.pubkey, + }; + } + + async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> { + // Query for patch event by converting number back to event ID + // This is a limitation - we'd need to store the mapping or query differently + throw new Error('Getting specific patches by number is not yet implemented for Nostr git'); + } + + async listPullRequests(owner: string, repo: string, state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequest[]> { + // Query for patch events (kind 1617) referencing this repository + const events = await this.relay.query([ + { + kinds: [1617], + '#a': [`30617:${owner}:${repo}`], + '#t': ['root'], // Only root patches, not replies + limit: 50, + } + ]); + + // For state filtering, we'd need to check status events (kind 1630-1633) + // For now, return all as 'open' + return events.map(event => ({ + number: parseInt(event.id.slice(0, 8), 16), + title: event.tags.find((t: string[]) => t[0] === 'subject')?.[1] || 'Untitled patch', + body: event.content, + state: 'open' as const, + headBranch: 'unknown', // Not stored in NIP-34 + baseBranch: 'unknown', // Not stored in NIP-34 + headRepo: `${event.pubkey}/${repo}`, + baseRepo: `${owner}/${repo}`, + url: `nostr:${event.id}`, + createdAt: new Date(event.created_at * 1000), + updatedAt: new Date(event.created_at * 1000), + author: event.pubkey, + })); + } + + async updatePullRequest(owner: string, repo: string, number: number, options: { title?: string; body?: string }): Promise<PullRequest> { + // In Nostr git, you can't edit events - you'd create a new revision + throw new Error('Updating patches is not supported - create a new revision instead'); + } + + async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> { + // To close a patch, publish a status event (kind 1632 - Closed) + throw new Error('Closing patches via status events is not yet implemented'); + } + + async getCurrentUser(): Promise<GitHostUser> { + // In Nostr, we can query the user's profile (kind 0) + const profiles = await this.relay.query([ + { + kinds: [0], + authors: [this.pubkey], + limit: 1, + } + ]); + + if (profiles.length > 0) { + const profile = JSON.parse(profiles[0].content); + return { + username: profile.name || this.pubkey.slice(0, 8), + name: profile.display_name || profile.name, + email: profile.nip05, + avatarUrl: profile.picture, + }; + } + + return { + username: this.pubkey.slice(0, 8), + }; + } + + getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string { + // Nostr git doesn't have a web compare view + // Could potentially link to a Nostr client that displays patches + return ''; + } +} diff --git a/src/lib/git-hosts/index.ts b/src/lib/git-hosts/index.ts index 861782a6..0896b894 100644 --- a/src/lib/git-hosts/index.ts +++ b/src/lib/git-hosts/index.ts @@ -2,10 +2,12 @@ export * from './types'; export { GitHubProvider } from './GitHubProvider'; export { GitLabProvider } from './GitLabProvider'; export { GiteaProvider } from './GiteaProvider'; +export { NostrGitProvider } from './NostrGitProvider'; import { GitHubProvider } from './GitHubProvider'; import { GitLabProvider } from './GitLabProvider'; import { GiteaProvider } from './GiteaProvider'; +import { NostrGitProvider } from './NostrGitProvider'; import { detectGitHost } from './types'; import type { GitHostProvider, GitHostConfig } from './types'; @@ -14,7 +16,7 @@ import type { GitHostProvider, GitHostConfig } from './types'; */ export function createGitHostProvider( url: string, - config: GitHostConfig, + config: GitHostConfig & { signer?: any; pubkey?: string; relayUrls?: string[] }, corsProxy?: string ): GitHostProvider | null { const hostType = detectGitHost(url); @@ -22,13 +24,13 @@ export function createGitHostProvider( switch (hostType) { case 'github': return new GitHubProvider(config, corsProxy); - + case 'gitlab': return new GitLabProvider(config, corsProxy); - + case 'codeberg': return new GiteaProvider(config, 'https://codeberg.org/api/v1', 'Codeberg', corsProxy); - + case 'gitea': // Extract API URL from repository URL try { @@ -38,7 +40,19 @@ export function createGitHostProvider( } catch { return null; } - + + case 'nostr': + // Nostr git requires signer and pubkey + if (!config.signer || !config.pubkey) { + throw new Error('Nostr git requires signer and pubkey in config'); + } + return new NostrGitProvider({ + token: config.token, + signer: config.signer, + pubkey: config.pubkey, + relayUrls: config.relayUrls || ['wss://relay.nostr.band'], + }); + default: return null; } diff --git a/src/lib/git-hosts/types.ts b/src/lib/git-hosts/types.ts index 92c2b81e..c359cf28 100644 --- a/src/lib/git-hosts/types.ts +++ b/src/lib/git-hosts/types.ts @@ -101,8 +101,13 @@ export interface GitHostProvider { /** * Detect Git host from repository URL */ -export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'unknown' { +export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'nostr' | 'unknown' { try { + // Check for Nostr git URLs (format: nostr://<pubkey>/<repo-id>) + if (url.startsWith('nostr://')) { + return 'nostr'; + } + const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, '')); const hostname = parsed.hostname.toLowerCase(); @@ -122,6 +127,17 @@ export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'cod */ export function parseRepoUrl(url: string): { owner: string; repo: string } | null { try { + // Handle Nostr git URLs (format: nostr://<pubkey>/<repo-id>) + if (url.startsWith('nostr://')) { + const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/); + if (match) { + return { + owner: match[1], // pubkey in hex + repo: match[2], // repo-id (d tag) + }; + } + } + // Handle git@ URLs const normalized = url.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, ''); const parsed = new URL(normalized);