Skip to content

🙌 OpenHands: AI-Driven Development

fix(automations): hide repository credentials on the Git Sync status card (#18039)

Engel Nyst99b5c7980d9d
diff --git a/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx b/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx
index 7c5c59653b..9592109119 100644
--- a/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx
+++ b/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx
@@ -81,6 +81,38 @@ describe("GitSyncOverviewSection", () => {
expect(link.getAttribute("href")).not.toContain("ghp_token");
});
+ // The card is on screen and in screen shares, so the label must not show
+ // credentials either. Tokens belong in the masked Access token field.
+ it.each([
+ [
+ "https://qa-user:[email protected]/qa-org/qa-repo.git",
+ "https://git.example.invalid/qa-org/qa-repo.git",
+ ],
+ // A token alone in the username slot is still a credential over https.
+ [
+ "https://[email protected]/org/repo.git",
+ "https://github.com/org/repo.git",
+ ],
+ // The ssh user is an account name, not a secret; only the password goes.
+ [
+ "ssh://git:[email protected]:2222/org/repo.git",
+ "ssh://[email protected]:2222/org/repo.git",
+ ],
+ ])("hides credentials in the label of %s", (repoUrl, label) => {
+ renderWith(repoUrl);
+
+ expect(screen.getByTestId("git-sync-repo-link").textContent).toBe(label);
+ });
+
+ // A remote with no repository path is not linked, but is still shown.
+ it("hides credentials in a remote rendered as plain text", () => {
+ renderWith("https://qa-user:[email protected]");
+
+ expect(screen.queryByTestId("git-sync-repo-link")).not.toBeInTheDocument();
+ expect(screen.getByText("https://git.example.invalid")).toBeInTheDocument();
+ expect(screen.queryByText(/qa-pass/)).not.toBeInTheDocument();
+ });
+
// A bare repo on disk is a valid sync target but has nothing to open.
it.each(["/tmp/git-sync-remote.git", "not a url", ""])(
"renders %s as plain text",
diff --git a/src/components/features/automations/git-sync/git-sync-overview-section.tsx b/src/components/features/automations/git-sync/git-sync-overview-section.tsx
index deb9cbeff4..2e7e8abb5a 100644
--- a/src/components/features/automations/git-sync/git-sync-overview-section.tsx
+++ b/src/components/features/automations/git-sync/git-sync-overview-section.tsx
@@ -44,6 +44,31 @@ function browseUrlFor(repoUrl: string): string | null {
return `https://${parsed.host}/${parsed.repository}`;
}
+// `scheme://userinfo@`; the greedy userinfo stops at the authority's last `@`,
+// where the WHATWG URL parser also ends it.
+const URL_USERINFO_PATTERN = /^([a-z][a-z\d+.-]*:\/\/)([^/?#]*)@/i;
+
+/**
+ * The configured remote as shown on the card, without embedded credentials.
+ * Like the href, an http(s) remote loses its whole userinfo, since a token
+ * often rides in the username slot alone. Other schemes keep the user, which
+ * names the account (`ssh://git@host`), and lose only a password. The rest of
+ * the value is shown exactly as configured.
+ */
+function displayUrlFor(repoUrl: string): string {
+ const url = repoUrl.trim();
+ const match = url.match(URL_USERINFO_PATTERN);
+ if (!match) return url;
+
+ const [userinfoPrefix, scheme, userinfo] = match;
+ const rest = url.slice(userinfoPrefix.length);
+ if (/^https?:\/\/$/i.test(scheme)) return `${scheme}${rest}`;
+
+ const passwordStart = userinfo.indexOf(":");
+ if (passwordStart === -1) return url;
+ return `${scheme}${userinfo.slice(0, passwordStart)}@${rest}`;
+}
+
interface GitSyncOverviewSectionProps {
status: GitSyncStatus;
onSyncNow: () => void;
@@ -63,6 +88,7 @@ export function GitSyncOverviewSection({
}: GitSyncOverviewSectionProps) {
const { t } = useTranslation("openhands");
const repoHref = browseUrlFor(status.repo_url);
+ const repoLabel = displayUrlFor(status.repo_url);
return (
<SectionCard
@@ -130,12 +156,11 @@ export function GitSyncOverviewSection({
rel="noopener noreferrer"
className="break-all underline transition-colors hover:text-foreground"
>
- {status.repo_url}
+ {repoLabel}
</a>
) : (
<span className="break-all">
- {status.repo_url ||
- t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_CONFIGURED)}
+ {repoLabel || t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_CONFIGURED)}
</span>
)}
</ConfigField>
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 3bd18fd4da..44ad11ca0c 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -43146,21 +43146,21 @@
"uk": "Увімкнути синхронізацію Git"
},
"AUTOMATIONS$GIT_SYNC$ENABLED_HELP": {
- "en": "Turn this off to pause syncing without losing the configuration. Turning it on requires a backend that was started with git sync enabled.",
- "ja": "オフにすると、設定を保持したまま同期を一時停止します。オンにするには、Git 同期を有効にして起動したバックエンドが必要です。",
- "zh-CN": "关闭后可暂停同步而不丢失配置。要开启,后端必须在启动时已启用 Git 同步。",
- "zh-TW": "關閉後可暫停同步而不遺失設定。要開啟,後端必須在啟動時已啟用 Git 同步。",
- "ko-KR": "끄면 설정을 유지한 채 동기화를 일시 중지합니다. 켜려면 Git 동기화가 활성화된 상태로 시작된 백엔드가 필요합니다.",
- "no": "Slå av for å sette synkroniseringen på pause uten å miste oppsettet. For å slå den på må backend være startet med Git-synkronisering aktivert.",
- "ar": "أوقف هذا الخيار لإيقاف المزامنة مؤقتًا دون فقدان الإعدادات. لتفعيله، يجب أن تكون الخدمة الخلفية قد بدأت مع تفعيل مزامنة Git.",
- "de": "Deaktivieren pausiert die Synchronisierung, ohne die Konfiguration zu verlieren. Zum Aktivieren muss das Backend mit aktivierter Git-Synchronisierung gestartet worden sein.",
- "fr": "Désactivez cette option pour mettre la synchronisation en pause sans perdre la configuration. Pour l'activer, le backend doit avoir démarré avec la synchronisation Git activée.",
- "it": "Disattiva per mettere in pausa la sincronizzazione senza perdere la configurazione. Per attivarla, il backend deve essere stato avviato con la sincronizzazione Git abilitata.",
- "pt": "Desative para pausar a sincronização sem perder a configuração. Para ativá-la, o backend precisa ter sido iniciado com a sincronização do Git ativada.",
- "es": "Desactívalo para pausar la sincronización sin perder la configuración. Para activarlo, el backend debe haberse iniciado con la sincronización de Git habilitada.",
- "ca": "Desactiva-ho per posar en pausa la sincronització sense perdre la configuració. Per activar-ho, el backend s'ha d'haver iniciat amb la sincronització de Git habilitada.",
- "tr": "Yapılandırmayı kaybetmeden eşitlemeyi duraklatmak için bunu kapatın. Açmak için arka ucun Git eşitlemesi etkin olarak başlatılmış olması gerekir.",
- "uk": "Вимкніть, щоб призупинити синхронізацію, не втрачаючи налаштування. Щоб увімкнути, бекенд має бути запущений з увімкненою синхронізацією Git."
+ "en": "Sync is on as soon as a repository is configured. Turn this off to pause syncing without losing the configuration.",
+ "ja": "リポジトリを設定すると、同期はすぐにオンになります。オフにすると、設定を保持したまま同期を一時停止します。",
+ "zh-CN": "配置仓库后,同步即会开启。关闭后可暂停同步而不丢失配置。",
+ "zh-TW": "設定儲存庫後,同步即會開啟。關閉後可暫停同步而不遺失設定。",
+ "ko-KR": "저장소를 구성하면 바로 동기화가 켜집니다. 끄면 설정을 유지한 채 동기화를 일시 중지합니다.",
+ "no": "Synkroniseringen er på så snart et repository er konfigurert. Slå av for å sette synkroniseringen på pause uten å miste oppsettet.",
+ "ar": "تعمل المزامنة بمجرد إعداد مستودع. أوقف هذا الخيار لإيقاف المزامنة مؤقتًا دون فقدان الإعدادات.",
+ "de": "Die Synchronisierung ist aktiv, sobald ein Repository konfiguriert ist. Deaktivieren pausiert die Synchronisierung, ohne die Konfiguration zu verlieren.",
+ "fr": "La synchronisation est active dès qu'un dépôt est configuré. Désactivez cette option pour mettre la synchronisation en pause sans perdre la configuration.",
+ "it": "La sincronizzazione è attiva non appena viene configurato un repository. Disattiva per mettere in pausa la sincronizzazione senza perdere la configurazione.",
+ "pt": "A sincronização fica ativa assim que um repositório é configurado. Desative para pausar a sincronização sem perder a configuração.",
+ "es": "La sincronización se activa en cuanto se configura un repositorio. Desactívalo para pausar la sincronización sin perder la configuración.",
+ "ca": "La sincronització s'activa tan bon punt es configura un repositori. Desactiva-ho per posar en pausa la sincronització sense perdre la configuració.",
+ "tr": "Bir depo yapılandırıldığı anda eşitleme açılır. Yapılandırmayı kaybetmeden eşitlemeyi duraklatmak için bunu kapatın.",
+ "uk": "Синхронізація вмикається, щойно налаштовано репозиторій. Вимкніть, щоб призупинити синхронізацію, не втрачаючи налаштування."
},
"AUTOMATIONS$GIT_SYNC$ENABLED": {
"en": "Enabled",
@@ -44862,57 +44862,6 @@
"uk": "Почнімо будувати!",
"ca": "Comencem a construir!"
},
- "AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR": {
- "en": "Git Sync must be enabled in the automation backend's environment, and the service restarted, before it can be turned on here.",
- "ja": "Git 同期を有効にするには、オートメーションバックエンドの環境で有効化し、サービスを再起動する必要があります。",
- "zh-CN": "必须先在自动化后端的环境中启用 Git 同步并重启服务,才能在此处开启。",
- "zh-TW": "必須先在自動化後端的環境中啟用 Git 同步並重新啟動服務,才能在此處開啟。",
- "ko-KR": "여기서 켜려면 먼저 자동화 백엔드 환경에서 Git 동기화를 활성화하고 서비스를 다시 시작해야 합니다.",
- "no": "Git-synkronisering må aktiveres i automatiserings-backendens miljø, og tjenesten må startes på nytt, før den kan slås på her.",
- "ar": "يجب تفعيل مزامنة Git في بيئة الخدمة الخلفية للأتمتة وإعادة تشغيل الخدمة قبل تفعيلها هنا.",
- "de": "Die Git-Synchronisierung muss in der Umgebung des Automatisierungs-Backends aktiviert und der Dienst neu gestartet werden, bevor sie hier eingeschaltet werden kann.",
- "fr": "La synchronisation Git doit être activée dans l'environnement du backend d'automatisation et le service redémarré avant de pouvoir l'activer ici.",
- "it": "La sincronizzazione Git deve essere abilitata nell'ambiente del backend di automazione e il servizio riavviato prima di poterla attivare qui.",
- "pt": "A sincronização do Git precisa ser ativada no ambiente do backend de automação, e o serviço reiniciado, antes de poder ser ligada aqui.",
- "es": "La sincronización de Git debe habilitarse en el entorno del backend de automatización y reiniciar el servicio antes de poder activarla aquí.",
- "ca": "La sincronització de Git s'ha d'habilitar a l'entorn del backend d'automatització i cal reiniciar el servei abans de poder activar-la aquí.",
- "tr": "Git eşitlemesi burada açılabilmesi için önce otomasyon arka ucunun ortamında etkinleştirilmeli ve hizmet yeniden başlatılmalıdır.",
- "uk": "Щоб увімкнути синхронізацію Git тут, її потрібно спершу активувати в середовищі бекенда автоматизації та перезапустити службу."
- },
- "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_TITLE": {
- "en": "Git Sync isn't available",
- "ja": "Git同期は利用できません",
- "zh-CN": "Git 同步不可用",
- "zh-TW": "Git 同步無法使用",
- "ko-KR": "Git 동기화를 사용할 수 없습니다",
- "no": "Git-synkronisering er ikke tilgjengelig",
- "ar": "مزامنة Git غير متاحة",
- "de": "Git-Synchronisierung ist nicht verfügbar",
- "fr": "La synchronisation Git n'est pas disponible",
- "it": "La sincronizzazione Git non è disponibile",
- "pt": "A sincronização Git não está disponível",
- "es": "La sincronización de Git no está disponible",
- "ca": "La sincronització de Git no està disponible",
- "tr": "Git Senkronizasyonu kullanılamıyor",
- "uk": "Git-синхронізація недоступна"
- },
- "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_MESSAGE": {
- "en": "Git Sync is only available when connected to a local OpenHands backend.",
- "ja": "Git同期はローカルのOpenHandsバックエンドに接続している場合のみ利用できます。",
- "zh-CN": "只有连接到本地 OpenHands 后端时才能使用 Git 同步。",
- "zh-TW": "只有連線到本機 OpenHands 後端時才能使用 Git 同步。",
- "ko-KR": "Git 동기화는 로컬 OpenHands 백엔드에 연결된 경우에만 사용할 수 있습니다.",
- "no": "Git-synkronisering er kun tilgjengelig når du er koblet til en lokal OpenHands-backend.",
- "ar": "تتوفر مزامنة Git فقط عند الاتصال بخلفية OpenHands محلية.",
- "de": "Git-Synchronisierung ist nur verfügbar, wenn eine Verbindung zu einem lokalen OpenHands-Backend besteht.",
- "fr": "La synchronisation Git n'est disponible que lorsque vous êtes connecté à un backend OpenHands local.",
- "it": "La sincronizzazione Git è disponibile solo quando sei connesso a un backend OpenHands locale.",
- "pt": "A sincronização Git só está disponível quando conectado a um backend OpenHands local.",
- "es": "La sincronización de Git solo está disponible al conectarse a un backend local de OpenHands.",
- "ca": "La sincronització de Git només està disponible en connectar-se a un backend local d'OpenHands.",
- "tr": "Git Senkronizasyonu yalnızca yerel bir OpenHands arka ucuna bağlıyken kullanılabilir.",
- "uk": "Git-синхронізація доступна лише при підключенні до локального бекенду OpenHands."
- },
"CHAT_INTERFACE$START_DICTATION": {
"en": "Start dictation",
"ja": "音声入力を開始",