mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Refactor to abstract repo announcement parsing
This commit is contained in:
1 parent
c474cd5c6c
commit
301b0d526b
7 files changed
+712
-393
No files matched your search
@@ -39,6 +39,7 @@ import {
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
@@ -209,21 +210,16 @@ export function AnnounceRepositoryDialog({
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse tags to populate form fields
|
||||
const nameTag = event.tags.find(([name]) => name === 'name');
|
||||
const descriptionTag = event.tags.find(([name]) => name === 'description');
|
||||
const webTag = event.tags.find(([name]) => name === 'web');
|
||||
const cloneTag = event.tags.find(([name]) => name === 'clone');
|
||||
const relaysTag = event.tags.find(([name]) => name === 'relays');
|
||||
const eucTag = event.tags.find(([name, , marker]) => name === 'r' && marker === 'euc');
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(identifier);
|
||||
setName(nameTag?.[1] || '');
|
||||
setDescription(descriptionTag?.[1] || '');
|
||||
setWebUrls(webTag ? webTag.slice(1) : []);
|
||||
setCloneUrls(cloneTag ? cloneTag.slice(1) : []);
|
||||
setRelays(relaysTag ? relaysTag.slice(1) : []);
|
||||
setEarliestCommit(eucTag?.[1] || '');
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
|
||||
@@ -39,6 +39,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
@@ -717,21 +718,20 @@ export function PullRequestDialog({
|
||||
const repoEvent = repoEvents[0];
|
||||
console.log('Found repository announcement event:', repoEvent);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get earliest unique commit from repository announcement
|
||||
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
|
||||
if (eucTag) {
|
||||
earliestUniqueCommit = eucTag[1];
|
||||
if (repoAnn.earliestCommit) {
|
||||
earliestUniqueCommit = repoAnn.earliestCommit;
|
||||
console.log('Found earliest unique commit:', earliestUniqueCommit);
|
||||
} else {
|
||||
console.warn('No euc tag found in repository announcement');
|
||||
}
|
||||
|
||||
// Get relay hints from repository announcement
|
||||
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
// Extract all relay URLs from the tag (skip the first element which is "relays")
|
||||
publishRelays = relayTag.slice(1);
|
||||
if (repoAnn.relays.length > 0) {
|
||||
publishRelays = repoAnn.relays;
|
||||
console.log('Publishing to repository relays:', publishRelays);
|
||||
} else {
|
||||
console.log('No relay hints in repository announcement, using configured relay');
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseRepositoryAnnouncement } from './announceRepository';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
// Valid test npub for GRASP URL testing
|
||||
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
|
||||
|
||||
|
||||
describe('parseRepositoryAnnouncement', () => {
|
||||
// Helper to create a mock repository announcement event
|
||||
const createMockEvent = (tags: string[][]): NostrEvent => ({
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
sig: 'test-sig',
|
||||
});
|
||||
|
||||
it('should throw error for non-30617 events', () => {
|
||||
const event = createMockEvent([]);
|
||||
event.kind = 1;
|
||||
|
||||
expect(() => parseRepositoryAnnouncement(event)).toThrow('Expected kind 30617, got 1');
|
||||
});
|
||||
|
||||
it('should parse basic repository fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'my-repo'],
|
||||
['name', 'My Repository'],
|
||||
['description', 'A test repository'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('my-repo');
|
||||
expect(result.name).toBe('My Repository');
|
||||
expect(result.description).toBe('A test repository');
|
||||
expect(result.httpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle missing optional fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'minimal-repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('minimal-repo');
|
||||
expect(result.name).toBeUndefined();
|
||||
expect(result.description).toBeUndefined();
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
expect(result.maintainers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should parse multiple values in single tag (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['web', 'https://example.com', 'https://mirror.example.com'],
|
||||
['clone', 'https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com', 'wss://relay2.com'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual(['https://example.com', 'https://mirror.example.com']);
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
expect(result.maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
|
||||
it('should parse multiple separate tags (backward compatibility)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com'],
|
||||
['relays', 'wss://relay2.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
});
|
||||
|
||||
it('should extract earliest unique commit (euc)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456', 'euc'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBe('abc123def456');
|
||||
});
|
||||
|
||||
it('should ignore r tags without euc marker', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456'],
|
||||
['r', 'other-value', 'other-marker'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
});
|
||||
|
||||
describe('graspServers - GRASP server detection', () => {
|
||||
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
expect(parsed.graspServers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(parsed.graspServers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should require both clone and relays tags to identify GRASP server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
// Missing relays tag for git.shakespeare.diy
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
// Missing clone tag for relay.ngit.dev
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`]);
|
||||
});
|
||||
|
||||
it('should validate npub pattern in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://git.shakespeare.diy/invalid-npub/myrepo.git']);
|
||||
});
|
||||
|
||||
it('should require .git extension in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo`]);
|
||||
});
|
||||
|
||||
it('should handle multiple clone URLs for same server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should reject http:// clone URLs and only accept https://', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
// Only https://relay.ngit.dev should be identified as GRASP server
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(servers).toHaveLength(1);
|
||||
// http:// URL should not be included in httpsCloneUrls at all
|
||||
expect(parsed.httpsCloneUrls).toEqual([`https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle ws and wss protocols', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'ws://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (separate tags)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should return empty array when no GRASP servers found', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['relays', 'wss://relay.nostr.band/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'not-a-valid-url'],
|
||||
['relays', 'also-invalid'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle paths with subdirectories after npub', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle empty tags array', () => {
|
||||
const event = createMockEvent([]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle tags with empty values', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', ''],
|
||||
['relays', ''],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle clone URLs with trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle relay URLs without trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle mixed trailing slashes in clone and relay URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out invalid URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://valid.com/repo.git', 'not-a-url', 'ftp://invalid.com/repo.git'],
|
||||
['relays', 'wss://valid.com', 'not-a-url', 'http://invalid.com'],
|
||||
['web', 'https://valid.com', 'not-a-url'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual(['https://valid.com/repo.git']);
|
||||
expect(result.relays).toEqual(['wss://valid.com']);
|
||||
expect(result.webUrls).toEqual(['https://valid.com', 'not-a-url']); // web URLs are not validated
|
||||
});
|
||||
|
||||
it('should preserve raw event', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.event).toBe(event);
|
||||
expect(result.event.id).toBe('test-id');
|
||||
expect(result.event.pubkey).toBe('test-pubkey');
|
||||
});
|
||||
|
||||
it('should handle empty identifier gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('');
|
||||
});
|
||||
|
||||
it('should handle empty arrays for missing multi-value tags', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual([]);
|
||||
expect(result.relays).toEqual([]);
|
||||
expect(result.maintainers).toEqual([]);
|
||||
expect(result.graspServers).toEqual([]);
|
||||
expect(result.nonGraspRelays).toEqual([]);
|
||||
});
|
||||
|
||||
it('should accept both ws and wss protocols for relays', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['relays', 'ws://insecure.example.com', 'wss://secure.example.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.relays).toEqual([
|
||||
'ws://insecure.example.com',
|
||||
'wss://secure.example.com',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should only accept https:// protocol for clone URLs (reject http://)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'http://insecure.example.com/repo.git', 'https://secure.example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Only https:// URL should be included
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://secure.example.com/repo.git',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EventTemplate } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export interface RepositoryAnnouncementData {
|
||||
@@ -18,6 +19,36 @@ export interface RepositoryAnnouncementData {
|
||||
earliestCommit?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsed NIP-34 repository announcement with categorized data
|
||||
*/
|
||||
export interface RepositoryAnnouncement {
|
||||
/** Repository identifier (d tag) */
|
||||
identifier: string;
|
||||
/** Human-readable name */
|
||||
name?: string;
|
||||
/** Description of the repository */
|
||||
description?: string;
|
||||
/** Web URLs where repository can be browsed */
|
||||
webUrls: string[];
|
||||
/** All clone URLs (https) - to support http we would need to store graspServers with ws|wss:// prefix */
|
||||
httpsCloneUrls: string[];
|
||||
/** valid ws:// or wss:// Repository relay URLs*/
|
||||
relays: string[];
|
||||
/** Earliest unique commit (root commit SHA) */
|
||||
earliestCommit?: string;
|
||||
/** Maintainer public keys */
|
||||
maintainers: string[];
|
||||
/** GRASP servers (hostname only) - servers that appear in both clone and relays with valid pattern */
|
||||
graspServers: string[];
|
||||
/** Clone URLs that are NOT GRASP servers */
|
||||
nonGraspHttpsCloneUrls: string[];
|
||||
/** Relay URLs that are NOT GRASP servers */
|
||||
nonGraspRelays: string[];
|
||||
/** Raw event for advanced use */
|
||||
event: NostrEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a NIP-34 repository announcement event (kind 30617)
|
||||
*
|
||||
@@ -150,3 +181,181 @@ export function validateRepositoryAnnouncementData(
|
||||
throw new Error('At least one clone URL is required');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a NIP-34 repository announcement event (kind 30617) into a structured format.
|
||||
*
|
||||
* This function extracts all relevant data from the event tags and categorizes servers
|
||||
* into GRASP and non-GRASP categories. GRASP servers are identified by matching:
|
||||
* - clone tag contains URL(s) matching: [http|https]://<hostname>/<valid-npub>/<repo>.git
|
||||
* - relays tag contains URL(s) matching: [ws|wss]://<hostname>
|
||||
*
|
||||
* @param event - A kind 30617 repository announcement event
|
||||
* @returns Parsed repository data with categorized servers
|
||||
* @throws Error if event is not kind 30617
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const repo = parseRepositoryAnnouncement(event);
|
||||
* console.log(repo.identifier); // "my-repo"
|
||||
* console.log(repo.graspServers); // ["git.example.com"]
|
||||
* console.log(repo.nonGraspCloneUrls); // ["https://github.com/user/repo.git"]
|
||||
* ```
|
||||
*/
|
||||
export function parseRepositoryAnnouncement(event: NostrEvent): RepositoryAnnouncement {
|
||||
if (event.kind !== 30617) {
|
||||
throw new Error(`Expected kind 30617, got ${event.kind}`);
|
||||
}
|
||||
|
||||
// Extract basic fields
|
||||
const identifier = event.tags.find(([name]) => name === 'd')?.[1] || '';
|
||||
const name = event.tags.find(([name]) => name === 'name')?.[1];
|
||||
const description = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
|
||||
// Extract multi-value tags
|
||||
const webUrls: string[] = [];
|
||||
const httpsCloneUrls: string[] = [];
|
||||
const relays: string[] = [];
|
||||
const maintainers: string[] = [];
|
||||
let earliestCommit: string | undefined;
|
||||
|
||||
// Track servers for GRASP detection
|
||||
const validCloneServers = new Set<string>(); // Servers with valid GRASP clone URLs
|
||||
const relayServers = new Set<string>(); // Servers in relays tags
|
||||
const cloneUrlsByServer = new Map<string, string[]>(); // Map hostname -> clone URLs
|
||||
const relayUrlsByServer = new Map<string, string[]>(); // Map hostname -> relay URLs
|
||||
|
||||
for (const [name, ...values] of event.tags) {
|
||||
switch (name) {
|
||||
case 'web':
|
||||
// All values after tag name are web URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
webUrls.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'clone':
|
||||
// All values after tag name are clone URLs
|
||||
// Also track which ones match GRASP pattern
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
|
||||
// Only accept https:// URLs (reject http://)
|
||||
if (url.protocol === 'https:') {
|
||||
httpsCloneUrls.push(value); // Use original value to preserve exact format
|
||||
|
||||
// Check if this matches GRASP pattern: https://<hostname>/<npub>/<repo>.git
|
||||
if ((value.endsWith('.git/') || value.endsWith('.git')) && value.includes('/npub1')) {
|
||||
// Extract and validate the npub using nip19.decode
|
||||
// Match npub1 followed by alphanumeric chars, ending at /
|
||||
const npubMatch = value.match(/\/npub1([a-z0-9]+)\//);
|
||||
if (npubMatch) {
|
||||
const npub = `npub1${npubMatch[1]}`;
|
||||
try {
|
||||
const decoded = nip19.decode(npub);
|
||||
if (decoded.type === 'npub') {
|
||||
// Valid GRASP clone URL
|
||||
validCloneServers.add(url.hostname);
|
||||
|
||||
if (!cloneUrlsByServer.has(url.hostname)) {
|
||||
cloneUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
cloneUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub, not a GRASP server
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'relays':
|
||||
// All values after tag name are relay URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
|
||||
relays.push(value); // Use original value to preserve exact format
|
||||
relayServers.add(url.hostname);
|
||||
|
||||
if (!relayUrlsByServer.has(url.hostname)) {
|
||||
relayUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
relayUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'maintainers':
|
||||
// All values after tag name are maintainer pubkeys
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
maintainers.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
// Check for earliest unique commit marker
|
||||
if (values.length >= 2 && values[1] === 'euc') {
|
||||
earliestCommit = values[0];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Identify GRASP servers: must appear in BOTH clone (with valid pattern) and relays
|
||||
const graspServers = [...validCloneServers].filter(server =>
|
||||
relayServers.has(server)
|
||||
);
|
||||
|
||||
// Categorize clone URLs
|
||||
const nonGraspHttpsCloneUrls = httpsCloneUrls.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
// Categorize relay URLs
|
||||
const nonGraspRelays = relays.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
httpsCloneUrls,
|
||||
relays,
|
||||
earliestCommit,
|
||||
maintainers,
|
||||
graspServers,
|
||||
nonGraspHttpsCloneUrls,
|
||||
nonGraspRelays,
|
||||
event,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
@@ -58,31 +59,23 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
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] || '';
|
||||
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
|
||||
const getRelays = () => {
|
||||
const relayTag = event.tags.find((t: string[]) => t[0] === 'relays');
|
||||
return relayTag ? relayTag.slice(1) : [];
|
||||
};
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Update relay to use repository's designated relays
|
||||
const repoRelays = getRelays();
|
||||
if (repoRelays.length > 0) {
|
||||
this.relayUrls = repoRelays;
|
||||
this.relay = new NRelay1(repoRelays[0]);
|
||||
if (repoAnn.relays.length > 0) {
|
||||
this.relayUrls = repoAnn.relays;
|
||||
this.relay = new NRelay1(repoAnn.relays[0]);
|
||||
}
|
||||
|
||||
return {
|
||||
owner,
|
||||
name: getName(),
|
||||
name: repoAnn.name || repo,
|
||||
fullName: `${owner}/${repo}`,
|
||||
defaultBranch: 'main', // Nostr git doesn't specify, assume main
|
||||
cloneUrl: getCloneUrl(),
|
||||
webUrl: getWebUrl(),
|
||||
description: getDescription(),
|
||||
cloneUrl: repoAnn.httpsCloneUrls[0] || '',
|
||||
webUrl: repoAnn.webUrls[0] || '',
|
||||
description: repoAnn.description,
|
||||
isPrivate: false, // All Nostr repos are public
|
||||
};
|
||||
}
|
||||
@@ -92,12 +85,12 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
// But only maintainers can apply them
|
||||
// Check if current user is listed as a maintainer
|
||||
const event = await this.queryRepo(owner, repo);
|
||||
// Per NIP-34, all maintainers are in a single tag: ["maintainers", "pubkey1", "pubkey2", ...]
|
||||
const maintainerTag = event.tags.find((t: string[]) => t[0] === 'maintainers');
|
||||
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Repo owner is always a maintainer
|
||||
const isMaintainer = owner === this.pubkey || maintainers.includes(this.pubkey);
|
||||
const isMaintainer = owner === this.pubkey || parsed.maintainers.includes(this.pubkey);
|
||||
return isMaintainer;
|
||||
}
|
||||
|
||||
@@ -106,8 +99,9 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
// 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] || '';
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// The "fork" is actually just the user's local copy
|
||||
// We'll use this to track that patches come from the user
|
||||
@@ -115,8 +109,8 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
owner: this.pubkey,
|
||||
name: repo,
|
||||
fullName: `${this.pubkey}/${repo}`,
|
||||
cloneUrl,
|
||||
webUrl,
|
||||
cloneUrl: parsed.httpsCloneUrls[0] || '',
|
||||
webUrl: parsed.webUrls[0] || '',
|
||||
parentFullName: `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
@@ -139,8 +133,11 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
const [owner, repo] = options.baseRepo.split('/');
|
||||
const repoEvent = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get the earliest unique commit (euc) for the repository
|
||||
const euc = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc')?.[1];
|
||||
const euc = parsed.earliestCommit;
|
||||
|
||||
// Create patch content from the provided body or generate a simple patch description
|
||||
const patchContent = options.body ||
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { getNgitServers } from './git';
|
||||
|
||||
// Valid test npub for GRASP URL testing
|
||||
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
|
||||
|
||||
// Helper to create a mock repository announcement event
|
||||
function createRepoEvent(tags: string[][]): NostrEvent {
|
||||
return {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags,
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
}
|
||||
|
||||
describe('getNgitServers', () => {
|
||||
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should require both clone and relays tags to identify GRASP server', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
// Missing relays tag for git.shakespeare.diy
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
// Missing clone tag for relay.ngit.dev
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should validate npub pattern in clone URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should require .git extension in clone URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should handle multiple clone URLs for same server', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle http and https protocols', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should handle ws and wss protocols', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'ws://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (separate tags)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should return empty array when no GRASP servers found', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['relays', 'wss://relay.nostr.band/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs gracefully', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'not-a-valid-url'],
|
||||
['relays', 'also-invalid'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle paths with subdirectories after npub', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle empty tags array', () => {
|
||||
const event = createRepoEvent([]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle tags with empty values', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', ''],
|
||||
['relays', ''],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle clone URLs with trailing slashes', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle relay URLs without trailing slashes', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle mixed trailing slashes in clone and relay URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+22
-126
@@ -3,6 +3,7 @@ import { NIP05 } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { proxyUrl } from './proxyUrl';
|
||||
import { readGitSettings } from './configUtils';
|
||||
import { parseRepositoryAnnouncement } from './announceRepository';
|
||||
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
@@ -638,20 +639,20 @@ export class Git {
|
||||
}
|
||||
} else {
|
||||
// No state event, try to get info from the first available clone URL
|
||||
const cloneUrls = getCloneURLs(repo);
|
||||
const repoAnn = parseRepositoryAnnouncement(repo);
|
||||
|
||||
if (cloneUrls.length > 0) {
|
||||
if (repoAnn.httpsCloneUrls.length > 0) {
|
||||
// Try to get remote info from the first clone URL
|
||||
try {
|
||||
const gitRemoteInfo = await git.getRemoteInfo({
|
||||
http: this.http,
|
||||
url: cloneUrls[0],
|
||||
url: repoAnn.httpsCloneUrls[0],
|
||||
});
|
||||
|
||||
Object.assign(refs, gitRemoteInfo.refs);
|
||||
HEAD = gitRemoteInfo.HEAD;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to get remote info from ${cloneUrls[0]}:`, error);
|
||||
console.warn(`Failed to get remote info from ${repoAnn.httpsCloneUrls[0]}:`, error);
|
||||
// Continue with empty refs if we can't get git remote info
|
||||
}
|
||||
}
|
||||
@@ -1023,8 +1024,7 @@ export class Git {
|
||||
const repoEvents = result.events.filter(e => e.kind === 30617);
|
||||
for (const repoEvent of repoEvents) {
|
||||
// Extract ngit servers from this announcement
|
||||
const discoveredServers = getNgitServers(repoEvent);
|
||||
for (const discoveredServer of discoveredServers) {
|
||||
for (const discoveredServer of parseRepositoryAnnouncement(repoEvent).graspServers) {
|
||||
if (!queriedServers.has(discoveredServer)) {
|
||||
serversToQuery.push(discoveredServer);
|
||||
}
|
||||
@@ -1069,8 +1069,7 @@ export class Git {
|
||||
}
|
||||
|
||||
// Get GRASP servers from the announcement and handle any mismatch
|
||||
const ngitServers = getNgitServers(latestRepo);
|
||||
this.processNgitServersMismatch(ngitServers);
|
||||
this.processNgitServersMismatch(parseRepositoryAnnouncement(latestRepo).graspServers);
|
||||
|
||||
// Analyze each ngitserver's status
|
||||
const serversWithoutAnnouncement: string[] = [];
|
||||
@@ -1134,9 +1133,9 @@ export class Git {
|
||||
}
|
||||
|
||||
// Collect valid clone URLs from the repo event tags
|
||||
const cloneUrls = getCloneURLs(repo);
|
||||
const repoAnn = parseRepositoryAnnouncement(repo);
|
||||
|
||||
if (cloneUrls.length === 0) {
|
||||
if (repoAnn.httpsCloneUrls.length === 0) {
|
||||
throw new Error('No valid clone URLs found in repository announcement');
|
||||
}
|
||||
|
||||
@@ -1147,7 +1146,7 @@ export class Git {
|
||||
if (expectedCommit) {
|
||||
console.log(`Looking for repository with commit: ${expectedCommit}`);
|
||||
|
||||
for (const cloneUrl of cloneUrls) {
|
||||
for (const cloneUrl of repoAnn.httpsCloneUrls) {
|
||||
try {
|
||||
console.log(`Checking remote info for: ${cloneUrl}`);
|
||||
|
||||
@@ -1223,7 +1222,7 @@ export class Git {
|
||||
if (!cloneSuccessful) {
|
||||
console.log('Falling back to regular clone from available URLs');
|
||||
|
||||
for (const cloneUrl of cloneUrls) {
|
||||
for (const cloneUrl of repoAnn.httpsCloneUrls) {
|
||||
try {
|
||||
console.log(`Attempting to clone from: ${cloneUrl}`);
|
||||
|
||||
@@ -1596,9 +1595,8 @@ export class Git {
|
||||
}
|
||||
}
|
||||
|
||||
// Get clone URLs using shared function (only https for push)
|
||||
const allCloneUrls = getCloneURLs(repo);
|
||||
const cloneUrls = allCloneUrls.filter(url => url.startsWith('https:'));
|
||||
// Get clone URLs using parseRepositoryAnnouncement (only https for push)
|
||||
const repoAnn = parseRepositoryAnnouncement(repo);
|
||||
|
||||
// If no relays specified in announcement, use default git-focused relays
|
||||
if (relayUrls.length === 0) {
|
||||
@@ -1664,8 +1662,8 @@ export class Git {
|
||||
}
|
||||
|
||||
// Push to each clone URL
|
||||
if (cloneUrls.length === 0) {
|
||||
console.warn('No Git clone URLs found in repository announcement');
|
||||
if (repoAnn.httpsCloneUrls.length === 0) {
|
||||
console.warn('No Git https clone URLs found in repository announcement');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1678,7 +1676,7 @@ export class Git {
|
||||
let pushSuccessful = false;
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (const cloneUrl of cloneUrls) {
|
||||
for (const cloneUrl of repoAnn.httpsCloneUrls) {
|
||||
console.log(`Pushing to Git remote: ${cloneUrl}`);
|
||||
|
||||
try {
|
||||
@@ -1708,15 +1706,15 @@ export class Git {
|
||||
|
||||
private async fetchMissingCommitsFromGitRemotes(repo: NostrEvent, dir: string, refs: Record<string, string>): Promise<void> {
|
||||
// Get clone URLs from the repository announcement
|
||||
const cloneUrls = getCloneURLs(repo);
|
||||
const repoAnn = parseRepositoryAnnouncement(repo);
|
||||
|
||||
if (cloneUrls.length === 0) {
|
||||
if (repoAnn.httpsCloneUrls.length === 0) {
|
||||
console.warn('No Git clone URLs available to fetch missing commits');
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to fetch missing commits from each Git remote
|
||||
for (const cloneUrl of cloneUrls) {
|
||||
for (const cloneUrl of repoAnn.httpsCloneUrls) {
|
||||
console.log(`Fetching missing commits from: ${cloneUrl}`);
|
||||
|
||||
try {
|
||||
@@ -1763,15 +1761,15 @@ export class Git {
|
||||
|
||||
private async fetchFromGitRemotes(repo: NostrEvent, dir: string): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> {
|
||||
// Get clone URLs from the repository announcement
|
||||
const cloneUrls = getCloneURLs(repo);
|
||||
const repoAnn = parseRepositoryAnnouncement(repo);
|
||||
|
||||
if (cloneUrls.length === 0) {
|
||||
if (repoAnn.httpsCloneUrls.length === 0) {
|
||||
throw new Error('No Git clone URLs available for fetching');
|
||||
}
|
||||
|
||||
// Try to fetch from each Git remote
|
||||
let lastError: Error | null = null;
|
||||
for (const cloneUrl of cloneUrls) {
|
||||
for (const cloneUrl of repoAnn.httpsCloneUrls) {
|
||||
try {
|
||||
console.log(`Fetching from Git remote: ${cloneUrl}`);
|
||||
|
||||
@@ -1867,108 +1865,6 @@ class GitHttp implements HttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract clone URLs from a Nostr repository event (kind 30617).
|
||||
* Collects all values from 'clone' tags and validates they are http/https URLs.
|
||||
*/
|
||||
function getCloneURLs(event: NostrEvent): string[] {
|
||||
const urls = new Set<string>();
|
||||
|
||||
for (const [name, ...values] of event.tags) {
|
||||
if (name === 'clone') {
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol === 'http:' || url.protocol === 'https:') {
|
||||
urls.add(url.href);
|
||||
}
|
||||
} catch {
|
||||
// Ignore invalid URLs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...urls];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract GRASP server hostnames from a Nostr repository event (kind 30617).
|
||||
*
|
||||
* GRASP servers are identified per NIP-34 by matching clone and relays tags:
|
||||
* - clone tag contains URL(s) matching: [http|https]://<hostname>/<valid-npub>/<repo>.git
|
||||
* - relays tag contains URL(s) matching: [ws|wss]://<hostname>
|
||||
*
|
||||
* NIP-34 format allows multiple values in a single tag:
|
||||
* ["clone", "url1", "url2", ...]
|
||||
* ["relays", "relay1", "relay2", ...]
|
||||
*
|
||||
* This function also handles multiple separate tags for backward compatibility.
|
||||
*
|
||||
* @param event - A kind 30617 repository announcement event
|
||||
* @returns Array of hostnames that are identified as GRASP servers
|
||||
*/
|
||||
export function getNgitServers(event: NostrEvent): string[] {
|
||||
// Track servers with valid GRASP clone URLs
|
||||
const validCloneServers = new Set<string>();
|
||||
|
||||
// Track servers in relays tags
|
||||
const relayServers = new Set<string>();
|
||||
|
||||
for (const [name, ...values] of event.tags) {
|
||||
if (name === 'clone') {
|
||||
// Check clone tags for GRASP pattern: https://<hostname>/<npub>/<repo>.git
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
// Must be http/https and end with .git
|
||||
if (!(value.startsWith('http://') || value.startsWith('https://'))) continue;
|
||||
if (!(value.endsWith('.git/') || value.endsWith('.git'))) continue;
|
||||
if (!value.includes('/npub1')) continue;
|
||||
|
||||
// Extract and validate the npub using nip19.decode
|
||||
// Find the npub1 part in the path
|
||||
const npubMatch = value.match(/\/npub1([a-z0-9]+)\//);
|
||||
if (!npubMatch) continue;
|
||||
|
||||
const npub = `npub1${npubMatch[1]}`;
|
||||
const decoded = nip19.decode(npub);
|
||||
if (decoded.type !== 'npub') continue;
|
||||
|
||||
// If we got here, it's a valid GRASP clone URL
|
||||
const url = new URL(value);
|
||||
validCloneServers.add(url.hostname);
|
||||
} catch {
|
||||
// Ignore invalid URLs or npub decode failures
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (name === 'relays') {
|
||||
// Check relays tags for websocket URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
|
||||
relayServers.add(url.hostname);
|
||||
}
|
||||
} catch {
|
||||
// Ignore invalid URLs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only include servers that appear in BOTH clone (with valid GRASP pattern) and relays tags
|
||||
const graspServers = [...validCloneServers].filter(server =>
|
||||
relayServers.has(server)
|
||||
);
|
||||
|
||||
return graspServers;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user