mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Refactor git credentials to be an array instead of an object
This commit is contained in:
12 files changed
+598
-220
No files matched your search
@@ -59,12 +59,14 @@ describe('GitDialog', () => {
|
||||
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -217,7 +219,7 @@ describe('GitDialog', () => {
|
||||
// Mock git settings with no credentials and mock git status with an https remote
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -18,31 +18,35 @@ function TestComponent() {
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
};
|
||||
addCredential('https://github.com', credential);
|
||||
addCredential(credential);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
updateCredential('https://github.com', { password: 'updated-token' });
|
||||
updateCredential(0, { password: 'updated-token' });
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
removeCredential('https://github.com');
|
||||
removeCredential(0);
|
||||
};
|
||||
|
||||
const githubCred = settings.credentials.find(c => c.host === 'github.com');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
|
||||
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
|
||||
<div data-testid="count">{settings.credentials.length}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
{githubCred && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
{settings.credentials['https://github.com'].password}
|
||||
{githubCred.username}:
|
||||
{githubCred.password}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -67,7 +71,7 @@ describe('GitSettingsProvider', () => {
|
||||
// Mock the read function to return default settings
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -164,12 +168,14 @@ describe('GitSettingsProvider', () => {
|
||||
expect(writeGitSettings).toHaveBeenCalledWith(
|
||||
expect.anything(), // fs instance
|
||||
expect.objectContaining({
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
}
|
||||
]
|
||||
}),
|
||||
'/config' // configPath
|
||||
);
|
||||
@@ -178,12 +184,14 @@ describe('GitSettingsProvider', () => {
|
||||
|
||||
it('loads settings from VFS', async () => {
|
||||
const settings = {
|
||||
credentials: {
|
||||
'https://gitlab.com': {
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'gitlab.com',
|
||||
username: 'git',
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
|
||||
@@ -9,7 +9,7 @@ interface GitSettingsProviderProps {
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
@@ -54,40 +54,35 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const addCredential = (origin: string, credential: GitCredential) => {
|
||||
const addCredential = (credential: GitCredential) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: credential,
|
||||
},
|
||||
credentials: [...prev.credentials, credential],
|
||||
}));
|
||||
};
|
||||
|
||||
const removeCredential = (origin: string) => {
|
||||
const removeCredential = (index: number) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: prev.credentials.filter((_, i) => i !== index),
|
||||
}));
|
||||
};
|
||||
|
||||
const updateCredential = (index: number, credential: Partial<GitCredential>) => {
|
||||
setSettings(prev => {
|
||||
const { [origin]: removed, ...rest } = prev.credentials;
|
||||
const newCredentials = [...prev.credentials];
|
||||
newCredentials[index] = {
|
||||
...newCredentials[index],
|
||||
...credential,
|
||||
};
|
||||
return {
|
||||
...prev,
|
||||
credentials: rest,
|
||||
credentials: newCredentials,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: {
|
||||
...prev.credentials[origin],
|
||||
...credential,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
const isConfigured = settings.credentials.length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
settings,
|
||||
|
||||
@@ -442,7 +442,7 @@ export function PullRequestDialog({
|
||||
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));
|
||||
console.log('Available credentials:', settings.credentials.map(c => `${c.protocol}://${c.host}`));
|
||||
|
||||
if (credentials) {
|
||||
console.log('Credential username:', credentials.username);
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface GitCredential {
|
||||
protocol: string;
|
||||
host: string; // Includes port if non-standard (e.g., "github.com:8080")
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface GitSettings {
|
||||
credentials: Record<string, GitCredential>; // keyed by origin
|
||||
credentials: GitCredential[];
|
||||
name?: string;
|
||||
email?: string;
|
||||
coAuthorEnabled?: boolean;
|
||||
@@ -15,9 +17,9 @@ export interface GitSettings {
|
||||
export interface GitSettingsContextType {
|
||||
settings: GitSettings;
|
||||
updateSettings: (settings: Partial<GitSettings>) => void;
|
||||
addCredential: (origin: string, credential: GitCredential) => void;
|
||||
removeCredential: (origin: string) => void;
|
||||
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
|
||||
addCredential: (credential: GitCredential) => void;
|
||||
removeCredential: (index: number) => void;
|
||||
updateCredential: (index: number, credential: Partial<GitCredential>) => void;
|
||||
isConfigured: boolean;
|
||||
isInitialized: boolean;
|
||||
}
|
||||
|
||||
@@ -71,7 +71,9 @@ export function useGitHubOAuth() {
|
||||
}
|
||||
|
||||
// Store the credentials
|
||||
addCredential('https://github.com', {
|
||||
addCredential({
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: result.username || 'git',
|
||||
password: result.accessToken,
|
||||
});
|
||||
|
||||
@@ -154,9 +154,20 @@ describe('configUtils', () => {
|
||||
});
|
||||
|
||||
describe('Git Settings', () => {
|
||||
const sampleGitSettings: GitSettings = {
|
||||
const sampleGitSettingsNew: GitSettings = {
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'token123',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const sampleGitSettingsOld = {
|
||||
credentials: {
|
||||
'github.com': {
|
||||
'https://github.com': {
|
||||
username: 'user',
|
||||
password: 'token123',
|
||||
},
|
||||
@@ -164,13 +175,57 @@ describe('configUtils', () => {
|
||||
};
|
||||
|
||||
describe('readGitSettings', () => {
|
||||
it('should read Git settings from VFS', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettings));
|
||||
it('should read Git settings from VFS (new format)', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettingsNew));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/config/git.json', 'utf8');
|
||||
expect(result).toEqual(sampleGitSettings);
|
||||
expect(result).toEqual(sampleGitSettingsNew);
|
||||
});
|
||||
|
||||
it('should convert old format to new format', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettingsOld));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/config/git.json', 'utf8');
|
||||
expect(result).toEqual({
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'token123',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle old format with custom ports', async () => {
|
||||
const oldFormatWithPort = {
|
||||
credentials: {
|
||||
'https://git.example.com:8080': {
|
||||
username: 'user',
|
||||
password: 'token456',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(oldFormatWithPort));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
credentials: [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'git.example.com:8080',
|
||||
username: 'user',
|
||||
password: 'token456',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should return default settings if file does not exist and no localStorage data', async () => {
|
||||
@@ -180,7 +235,7 @@ describe('configUtils', () => {
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
coAuthorEnabled: true,
|
||||
});
|
||||
});
|
||||
@@ -192,12 +247,12 @@ describe('configUtils', () => {
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
await writeGitSettings(mockFS, sampleGitSettings);
|
||||
await writeGitSettings(mockFS, sampleGitSettingsNew);
|
||||
|
||||
expect(mockFS.mkdir).toHaveBeenCalledWith('/config', { recursive: true });
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/git.json',
|
||||
JSON.stringify(sampleGitSettings, null, 2),
|
||||
JSON.stringify(sampleGitSettingsNew, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
|
||||
+47
-4
@@ -3,7 +3,7 @@ import { filteredArray } from '@/lib/schema';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
|
||||
|
||||
/**
|
||||
@@ -57,13 +57,26 @@ const aiSettingsSchema = z.object({
|
||||
mcpServers: z.record(z.string(), mcpServerSchema).optional(),
|
||||
});
|
||||
|
||||
// New format for git credentials
|
||||
const gitCredentialSchema = z.object({
|
||||
protocol: z.string(),
|
||||
host: z.string(),
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
// Old format (map of origins to credentials)
|
||||
const gitCredentialOldSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
// Schema that accepts both old and new formats
|
||||
const gitSettingsSchema = z.object({
|
||||
credentials: z.record(z.string(), gitCredentialSchema),
|
||||
credentials: z.union([
|
||||
z.array(gitCredentialSchema), // New format: array
|
||||
z.record(z.string(), gitCredentialOldSchema), // Old format: map
|
||||
]),
|
||||
name: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
coAuthorEnabled: z.boolean().optional(),
|
||||
@@ -204,6 +217,23 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, con
|
||||
await fs.writeFile(aiConfigPath, JSON.stringify(settings, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert old format credentials (map) to new format (array)
|
||||
*/
|
||||
function convertCredentialsToNewFormat(
|
||||
credentials: Record<string, { username: string; password: string }>
|
||||
): GitCredential[] {
|
||||
return Object.entries(credentials).map(([origin, cred]) => {
|
||||
const url = new URL(origin);
|
||||
return {
|
||||
protocol: url.protocol.replace(/:$/, ''),
|
||||
host: url.host, // Includes port if non-standard
|
||||
username: cred.username,
|
||||
password: cred.password,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Git settings from VFS
|
||||
* @param fs - Filesystem instance
|
||||
@@ -211,7 +241,7 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, con
|
||||
*/
|
||||
export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'): Promise<GitSettings> {
|
||||
const defaultSettings: GitSettings = {
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
coAuthorEnabled: true,
|
||||
};
|
||||
|
||||
@@ -220,7 +250,20 @@ export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'):
|
||||
const gitConfigPath = getGitConfigPath(configPath);
|
||||
const content = await fs.readFile(gitConfigPath, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return gitSettingsSchema.parse(data);
|
||||
const parsed = gitSettingsSchema.parse(data);
|
||||
|
||||
// Convert old format to new format if needed
|
||||
let credentials: GitCredential[];
|
||||
if (Array.isArray(parsed.credentials)) {
|
||||
credentials = parsed.credentials;
|
||||
} else {
|
||||
credentials = convertCredentialsToNewFormat(parsed.credentials);
|
||||
}
|
||||
|
||||
return {
|
||||
...parsed,
|
||||
credentials,
|
||||
};
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
+4
-4
@@ -305,7 +305,7 @@ describe('Git', () => {
|
||||
it('uses shakespeare.diy as default author when no Git identity is configured', async () => {
|
||||
const { readGitSettings } = await import('./configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
coAuthorEnabled: true,
|
||||
});
|
||||
|
||||
@@ -332,7 +332,7 @@ describe('Git', () => {
|
||||
it('uses custom identity when both name and email are configured', async () => {
|
||||
const { readGitSettings } = await import('./configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
name: 'John Doe',
|
||||
email: '[email protected]',
|
||||
coAuthorEnabled: true,
|
||||
@@ -361,7 +361,7 @@ describe('Git', () => {
|
||||
it('does not add co-author when coAuthorEnabled is false', async () => {
|
||||
const { readGitSettings } = await import('./configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
name: 'John Doe',
|
||||
email: '[email protected]',
|
||||
coAuthorEnabled: false,
|
||||
@@ -390,7 +390,7 @@ describe('Git', () => {
|
||||
it('respects provided author when explicitly passed', async () => {
|
||||
const { readGitSettings } = await import('./configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
credentials: [],
|
||||
name: 'John Doe',
|
||||
email: '[email protected]',
|
||||
coAuthorEnabled: true,
|
||||
|
||||
+316
-75
@@ -1,92 +1,333 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { extractGitOrigin, findCredentialsForRepo, getOriginDisplayName } from './gitCredentials';
|
||||
import { findCredentialsForRepo } from './gitCredentials';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
describe('gitCredentials', () => {
|
||||
describe('extractGitOrigin', () => {
|
||||
it('should extract origin from HTTPS URLs', () => {
|
||||
expect(extractGitOrigin('https://github.com/user/repo.git')).toBe('https://github.com');
|
||||
expect(extractGitOrigin('https://gitlab.com/user/repo.git')).toBe('https://gitlab.com');
|
||||
expect(extractGitOrigin('https://git.example.com:8080/user/repo.git')).toBe('https://git.example.com:8080');
|
||||
});
|
||||
|
||||
it('should extract origin from HTTP URLs', () => {
|
||||
expect(extractGitOrigin('http://git.example.com/user/repo.git')).toBe('http://git.example.com');
|
||||
});
|
||||
|
||||
it('should extract origin from SSH URLs', () => {
|
||||
expect(extractGitOrigin('[email protected]:user/repo.git')).toBe('https://github.com');
|
||||
expect(extractGitOrigin('[email protected]:user/repo.git')).toBe('https://gitlab.com');
|
||||
expect(extractGitOrigin('[email protected]:user/repo.git')).toBe('https://git.example.com');
|
||||
});
|
||||
|
||||
it('should return null for invalid URLs', () => {
|
||||
expect(extractGitOrigin('')).toBe(null);
|
||||
expect(extractGitOrigin('invalid-url')).toBe(null);
|
||||
expect(extractGitOrigin('ftp://example.com/repo')).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findCredentialsForRepo', () => {
|
||||
const mockCredentials: Record<string, GitCredential> = {
|
||||
'https://github.com': { username: 'git', password: 'github-token' },
|
||||
'https://gitlab.com': { username: 'git', password: 'gitlab-token' },
|
||||
'https://git.example.com': { username: 'user', password: 'custom-token' },
|
||||
};
|
||||
|
||||
it('should find exact matches', () => {
|
||||
expect(findCredentialsForRepo('https://github.com/user/repo.git', mockCredentials))
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
|
||||
expect(findCredentialsForRepo('https://gitlab.com/user/repo.git', mockCredentials))
|
||||
.toEqual({ username: 'git', password: 'gitlab-token' });
|
||||
it('returns undefined when no credentials are provided', () => {
|
||||
const result = findCredentialsForRepo('https://github.com/user/repo.git', []);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should find matches for SSH URLs', () => {
|
||||
expect(findCredentialsForRepo('[email protected]:user/repo.git', mockCredentials))
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
it('returns undefined when no credentials match', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'gitlab.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/user/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle case-insensitive matching', () => {
|
||||
expect(findCredentialsForRepo('https://GitHub.com/user/repo.git', mockCredentials))
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
it('matches credential with exact protocol, hostname, and default port', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/user/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('should handle www variations', () => {
|
||||
const credentialsWithWww = {
|
||||
'https://www.github.com': { username: 'git', password: 'github-token' },
|
||||
};
|
||||
|
||||
expect(findCredentialsForRepo('https://github.com/user/repo.git', credentialsWithWww))
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
|
||||
expect(findCredentialsForRepo('https://www.github.com/user/repo.git', mockCredentials))
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
it('matches credential with explicit port 443 for https', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com:443',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/user/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('should return undefined when no credentials found', () => {
|
||||
expect(findCredentialsForRepo('https://unknown.com/user/repo.git', mockCredentials))
|
||||
.toBe(undefined);
|
||||
|
||||
expect(findCredentialsForRepo('invalid-url', mockCredentials))
|
||||
.toBe(undefined);
|
||||
it('matches credential with explicit port 80 for http', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'http',
|
||||
host: 'example.com:80',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('http://example.com/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('should return undefined for empty credentials', () => {
|
||||
expect(findCredentialsForRepo('https://github.com/user/repo.git', {}))
|
||||
.toBe(undefined);
|
||||
it('matches credential with custom port when URL has same custom port', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'gitlab.local:8443',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://gitlab.local:8443/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('does not match when ports differ', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'gitlab.local:8443',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://gitlab.local:9443/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not match when protocol differs', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'http',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/user/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not match when hostname differs', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://gitlab.com/user/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('prefers credential with matching username over credential without username', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'pass1',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'alice',
|
||||
password: 'pass2',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://[email protected]/repo.git', credentials);
|
||||
expect(result).toBe(credentials[1]);
|
||||
});
|
||||
|
||||
it('returns first match when no username preference exists', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'pass1',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'pass2',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('does not match when usernames differ', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'alice',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://[email protected]/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('matches when credential has username but URL does not', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'alice',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('matches when URL has username but credential does not', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://[email protected]/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('handles multiple matching credentials and returns the one with matching username', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'alice',
|
||||
password: 'pass1',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'bob',
|
||||
password: 'pass2',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'pass3',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://[email protected]/repo.git', credentials);
|
||||
expect(result).toBe(credentials[1]);
|
||||
});
|
||||
|
||||
it('handles complex URLs with paths and query parameters', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo(
|
||||
'https://github.com/org/repo.git?foo=bar#fragment',
|
||||
credentials
|
||||
);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('handles URLs with encoded characters', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: 'user%40email.com',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo(
|
||||
'https://user%[email protected]/repo.git',
|
||||
credentials
|
||||
);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('handles subdomains correctly', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'api.github.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
// Should not match github.com
|
||||
const result1 = findCredentialsForRepo('https://github.com/repo.git', credentials);
|
||||
expect(result1).toBeUndefined();
|
||||
|
||||
// Should match api.github.com
|
||||
const result2 = findCredentialsForRepo('https://api.github.com/repo.git', credentials);
|
||||
expect(result2).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('handles credentials with empty username', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'token',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('returns credential when both URL and credential have no username', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'https',
|
||||
host: 'github.com',
|
||||
username: '',
|
||||
password: 'token',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('https://github.com/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('handles IPv4 addresses as hostnames', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'http',
|
||||
host: '192.168.1.100:8080',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('http://192.168.1.100:8080/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
|
||||
it('does not match IPv4 addresses with different ports', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'http',
|
||||
host: '192.168.1.100:8080',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('http://192.168.1.100:9090/repo.git', credentials);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('handles localhost URLs', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{
|
||||
protocol: 'http',
|
||||
host: 'localhost:3000',
|
||||
username: 'dev',
|
||||
password: 'pass',
|
||||
},
|
||||
];
|
||||
const result = findCredentialsForRepo('http://localhost:3000/repo.git', credentials);
|
||||
expect(result).toBe(credentials[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOriginDisplayName', () => {
|
||||
it('should extract hostname from valid URLs', () => {
|
||||
expect(getOriginDisplayName('https://github.com')).toBe('github.com');
|
||||
expect(getOriginDisplayName('https://git.example.com:8080')).toBe('git.example.com:8080');
|
||||
});
|
||||
|
||||
it('should return original string for invalid URLs', () => {
|
||||
expect(getOriginDisplayName('invalid-url')).toBe('invalid-url');
|
||||
expect(getOriginDisplayName('')).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+62
-59
@@ -1,72 +1,75 @@
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
/**
|
||||
* Extract the origin (protocol + hostname + port) from a Git URL
|
||||
* Get the effective port for a URL (considering defaults)
|
||||
*/
|
||||
export function extractGitOrigin(gitUrl: string): string | null {
|
||||
try {
|
||||
// Handle SSH URLs like [email protected]:user/repo.git
|
||||
if (gitUrl.startsWith('git@')) {
|
||||
const match = gitUrl.match(/^git@([^:]+):/);
|
||||
if (match) {
|
||||
return `https://${match[1]}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle HTTP/HTTPS URLs
|
||||
if (gitUrl.startsWith('http://') || gitUrl.startsWith('https://')) {
|
||||
const url = new URL(gitUrl);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
function getEffectivePort(url: URL): number | undefined {
|
||||
if (url.port) {
|
||||
return parseInt(url.port);
|
||||
}
|
||||
switch (url.protocol) {
|
||||
case 'http:':
|
||||
return 80;
|
||||
case 'https:':
|
||||
return 443;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find matching credentials for a repository URL
|
||||
* Match a URL against a credential
|
||||
* Returns true if the credential matches the URL
|
||||
*/
|
||||
function matchesCredential(
|
||||
credential: GitCredential,
|
||||
urlString: string
|
||||
): boolean {
|
||||
const targetURL = new URL(urlString);
|
||||
const credURL = new URL(`${credential.protocol}://${credential.host}/`);
|
||||
|
||||
// 1. Protocol must match exactly
|
||||
if (credURL.protocol !== targetURL.protocol) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. Hostname must match exactly
|
||||
if (credURL.hostname !== targetURL.hostname) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. Port must match exactly (after default conversion)
|
||||
if (getEffectivePort(credURL) !== getEffectivePort(targetURL)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4. Username must match if both are specified
|
||||
if (credential.username && targetURL.username) {
|
||||
if (credential.username !== targetURL.username) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the best matching credential for a URL from a list of credentials
|
||||
* Returns the credential with username match preferred over no username
|
||||
*/
|
||||
export function findCredentialsForRepo(
|
||||
repoUrl: string,
|
||||
credentials: Record<string, GitCredential>
|
||||
urlString: string,
|
||||
credentials: GitCredential[],
|
||||
): GitCredential | undefined {
|
||||
const repoOrigin = extractGitOrigin(repoUrl);
|
||||
if (!repoOrigin) return;
|
||||
|
||||
// Direct match
|
||||
if (credentials[repoOrigin]) {
|
||||
return credentials[repoOrigin];
|
||||
}
|
||||
|
||||
// Try to find a match by normalizing common variations
|
||||
const normalizedRepoOrigin = repoOrigin.toLowerCase();
|
||||
|
||||
for (const [origin, credential] of Object.entries(credentials)) {
|
||||
const normalizedOrigin = origin.toLowerCase();
|
||||
|
||||
// Exact match (case-insensitive)
|
||||
if (normalizedOrigin === normalizedRepoOrigin) {
|
||||
return credential;
|
||||
}
|
||||
|
||||
// Handle www variations
|
||||
if (normalizedOrigin.replace(/^https?:\/\/www\./, 'https://') ===
|
||||
normalizedRepoOrigin.replace(/^https?:\/\/www\./, 'https://')) {
|
||||
return credential;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the display name for a Git origin URL
|
||||
*/
|
||||
export function getOriginDisplayName(origin: string): string {
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
return url.host; // Use host instead of hostname to include port
|
||||
} catch {
|
||||
return origin;
|
||||
const targetURL = new URL(urlString);
|
||||
const matches = credentials.filter(cred => matchesCredential(cred, urlString));
|
||||
|
||||
if (matches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Prefer credentials with matching username
|
||||
const withUsername = matches.find(
|
||||
cred => cred.username && cred.username === targetURL.username,
|
||||
);
|
||||
|
||||
return withUsername ?? matches[0];
|
||||
}
|
||||
+50
-23
@@ -60,18 +60,37 @@ export function GitSettings() {
|
||||
const [presetTokens, setPresetTokens] = useState<Record<string, string>>({});
|
||||
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
|
||||
|
||||
// Helper to parse origin URL into credential parts
|
||||
const parseOrigin = (origin: string): { protocol: string; host: string } => {
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
return {
|
||||
protocol: url.protocol.replace(':', ''), // Remove trailing colon
|
||||
host: url.host, // Includes port if non-standard (e.g., "github.com:8080")
|
||||
};
|
||||
} catch {
|
||||
// Fallback: assume https and treat as hostname
|
||||
return {
|
||||
protocol: 'https',
|
||||
host: origin,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetProvider) => {
|
||||
const token = presetTokens[preset.id] as string | undefined;
|
||||
|
||||
if (!token?.trim()) return;
|
||||
|
||||
const parsed = parseOrigin(preset.origin);
|
||||
const newCredential: GitCredential = {
|
||||
...parsed,
|
||||
username: preset.username,
|
||||
password: token.trim(),
|
||||
};
|
||||
|
||||
// Auto-save: Add credential immediately to persistent storage
|
||||
addCredential(preset.origin, newCredential);
|
||||
addCredential(newCredential);
|
||||
|
||||
// Clear the token input for this preset
|
||||
setPresetTokens(prev => ({
|
||||
@@ -83,30 +102,38 @@ export function GitSettings() {
|
||||
const handleAddCustomProvider = () => {
|
||||
if (!customOrigin.trim() || !customUsername.trim() || !customPassword.trim()) return;
|
||||
|
||||
const parsed = parseOrigin(customOrigin.trim());
|
||||
const newCredential: GitCredential = {
|
||||
...parsed,
|
||||
username: customUsername.trim(),
|
||||
password: customPassword.trim(),
|
||||
};
|
||||
|
||||
// Auto-save: Add credential immediately to persistent storage
|
||||
addCredential(customOrigin.trim(), newCredential);
|
||||
addCredential(newCredential);
|
||||
|
||||
setCustomOrigin('');
|
||||
setCustomUsername('');
|
||||
setCustomPassword('');
|
||||
};
|
||||
|
||||
const handleRemoveCredential = (origin: string) => {
|
||||
const handleRemoveCredential = (index: number) => {
|
||||
// Auto-save: Remove credential immediately from persistent storage
|
||||
removeCredential(origin);
|
||||
removeCredential(index);
|
||||
};
|
||||
|
||||
const handleUpdateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
const handleUpdateCredential = (index: number, credential: Partial<GitCredential>) => {
|
||||
// Auto-save: Update credential immediately in persistent storage
|
||||
updateCredential(origin, credential);
|
||||
updateCredential(index, credential);
|
||||
};
|
||||
|
||||
const configuredOrigins = Object.keys(settings.credentials);
|
||||
// Helper to get origin string from credential
|
||||
const getOriginFromCredential = (cred: GitCredential): string => {
|
||||
return `${cred.protocol}://${cred.host}`; // host already includes port if non-standard
|
||||
};
|
||||
|
||||
// Get list of configured origins
|
||||
const configuredOrigins = settings.credentials.map(getOriginFromCredential);
|
||||
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredOrigins.includes(preset.origin));
|
||||
|
||||
return (
|
||||
@@ -148,17 +175,17 @@ export function GitSettings() {
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Configured Credentials */}
|
||||
{configuredOrigins.length > 0 && (
|
||||
{settings.credentials.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">{t('configuredCredentials')}</h4>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{configuredOrigins.map((origin) => {
|
||||
{settings.credentials.map((credential, index) => {
|
||||
const origin = getOriginFromCredential(credential);
|
||||
const preset = PRESET_PROVIDERS.find(p => p.origin === origin);
|
||||
const credential = settings.credentials[origin];
|
||||
const isCustom = !preset;
|
||||
|
||||
return (
|
||||
<AccordionItem key={origin} value={origin}>
|
||||
<AccordionItem key={`${origin}-${index}`} value={`${origin}-${index}`}>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
@@ -167,7 +194,7 @@ export function GitSettings() {
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<span className="font-medium">
|
||||
{preset?.name || new URL(origin).hostname}
|
||||
{preset?.name || credential.host}
|
||||
</span>
|
||||
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
|
||||
</div>
|
||||
@@ -175,11 +202,11 @@ export function GitSettings() {
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${origin}-origin`}>
|
||||
<Label htmlFor={`${origin}-${index}-origin`}>
|
||||
{t('origin')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`${origin}-origin`}
|
||||
id={`${origin}-${index}-origin`}
|
||||
placeholder="https://github.com"
|
||||
value={origin}
|
||||
disabled
|
||||
@@ -187,31 +214,31 @@ export function GitSettings() {
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${origin}-username`}>
|
||||
<Label htmlFor={`${origin}-${index}-username`}>
|
||||
{t('username')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`${origin}-username`}
|
||||
id={`${origin}-${index}-username`}
|
||||
placeholder="git"
|
||||
value={credential?.username || ''}
|
||||
onChange={(e) => handleUpdateCredential(origin, { username: e.target.value })}
|
||||
value={credential.username}
|
||||
onChange={(e) => handleUpdateCredential(index, { username: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${origin}-password`}>
|
||||
<Label htmlFor={`${origin}-${index}-password`}>
|
||||
{t('password')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id={`${origin}-password`}
|
||||
id={`${origin}-${index}-password`}
|
||||
placeholder={t('enterPassword')}
|
||||
value={credential?.password || ''}
|
||||
onChange={(e) => handleUpdateCredential(origin, { password: e.target.value })}
|
||||
value={credential.password}
|
||||
onChange={(e) => handleUpdateCredential(index, { password: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveCredential(origin)}
|
||||
onClick={() => handleRemoveCredential(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
|
||||
Reference in new issue
Block a user