Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(gitea-integration): structured failure response and test coverage

justin49eac382cc8f
diff --git a/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts b/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
index 040a7e2b1..fba7adff0 100644
--- a/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
+++ b/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
@@ -1,8 +1,8 @@
import { HTTPException } from "hono/http-exception";
import { normalizeGiteaBaseUrl } from "../../plugins/gitea/config";
import {
- GiteaApiError,
createGiteaClient,
+ GiteaApiError,
verifyGiteaToken,
} from "../../plugins/gitea/utils/gitea-api";
@@ -40,23 +40,35 @@ async function verifyGiteaAccess({
message: hasIssuesWrite
? "Token can access the repository."
: "Token may not have sufficient permissions to manage issues.",
+ failureReason: null,
};
} catch (error) {
const err = error as { status?: number; message?: string };
- if (
- error instanceof GiteaApiError &&
- (error.message.includes("invalid JSON") ||
- error.message.includes("was redirected"))
- ) {
- return {
- isInstalled: false,
- hasRequiredPermissions: false,
- repositoryExists: false,
- repositoryPrivate: null,
- missingPermissions: [] as string[],
- message: "The URL does not point to a Gitea instance.",
- };
+ if (error instanceof GiteaApiError) {
+ if (error.kind === "REDIRECT") {
+ return {
+ isInstalled: false,
+ hasRequiredPermissions: false,
+ repositoryExists: false,
+ repositoryPrivate: null,
+ missingPermissions: [] as string[],
+ message: `The Gitea URL redirected (HTTP ${error.status}). This usually means the server forces HTTPS. Please use the final URL directly.`,
+ failureReason: "redirected",
+ };
+ }
+
+ if (error.kind === "INVALID_JSON") {
+ return {
+ isInstalled: false,
+ hasRequiredPermissions: false,
+ repositoryExists: false,
+ repositoryPrivate: null,
+ missingPermissions: [] as string[],
+ message: "The URL does not point to a Gitea instance.",
+ failureReason: "not_a_gitea_instance",
+ };
+ }
}
if (err.status === 404) {
@@ -67,6 +79,7 @@ async function verifyGiteaAccess({
repositoryPrivate: null,
missingPermissions: [] as string[],
message: "Repository not found or not accessible with this token.",
+ failureReason: "repository_not_found",
};
}
diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.ts
index 50cb3a40c..e15d2dec3 100644
--- a/apps/api/src/gitea-integration/index.ts
+++ b/apps/api/src/gitea-integration/index.ts
@@ -43,6 +43,9 @@ const verificationResultSchema = v.object({
repositoryPrivate: v.nullable(v.boolean()),
missingPermissions: v.array(v.string()),
message: v.string(),
+ failureReason: v.nullable(
+ v.picklist(["not_a_gitea_instance", "redirected", "repository_not_found"]),
+ ),
});
const importResultSchema = v.object({
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
index aba4712de..cefc65117 100644
--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -40,10 +40,18 @@ export type GiteaPullRequest = {
merged_at?: string | null;
};
+export type GiteaApiErrorKind =
+ | "REDIRECT"
+ | "INVALID_JSON"
+ | "HTTP_ERROR"
+ | "TIMEOUT"
+ | "EMPTY_RESPONSE";
+
export class GiteaApiError extends Error {
constructor(
message: string,
public status: number,
+ public kind: GiteaApiErrorKind,
public body?: string,
) {
super(message);
@@ -101,7 +109,11 @@ export async function giteaFetch<T>(
});
if (res.status >= 300 && res.status < 400) {
- throw new GiteaApiError("Gitea request was redirected", res.status);
+ throw new GiteaApiError(
+ `Gitea request was redirected (HTTP ${res.status})`,
+ res.status,
+ "REDIRECT",
+ );
}
const text = await res.text();
@@ -111,6 +123,7 @@ export async function giteaFetch<T>(
throw new GiteaApiError(
`Gitea API error ${res.status}`,
res.status,
+ "HTTP_ERROR",
text,
);
}
@@ -125,6 +138,7 @@ export async function giteaFetch<T>(
throw new GiteaApiError(
"Gitea API returned invalid JSON",
res.status,
+ "INVALID_JSON",
text,
);
}
@@ -138,6 +152,7 @@ export async function giteaFetch<T>(
throw new GiteaApiError(
`Gitea request timed out after ${GITEA_FETCH_TIMEOUT_MS}ms`,
408,
+ "TIMEOUT",
);
}
throw error;
@@ -172,7 +187,11 @@ export function createGiteaClient(
permissions?: { admin?: boolean; push?: boolean; pull?: boolean };
}>(baseUrl, accessToken, owner(repositoryOwner, repositoryName));
if (!repo) {
- throw new GiteaApiError("Gitea repository response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea repository response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return repo;
},
@@ -201,7 +220,11 @@ export function createGiteaClient(
}>
>(baseUrl, accessToken, `/user/repos?page=${page}&limit=${limit}`);
if (!repos) {
- throw new GiteaApiError("Gitea repositories response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea repositories response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return repos;
},
@@ -221,7 +244,11 @@ export function createGiteaClient(
},
);
if (!issue) {
- throw new GiteaApiError("Gitea create issue response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea create issue response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return issue;
},
@@ -242,7 +269,11 @@ export function createGiteaClient(
},
);
if (!issue) {
- throw new GiteaApiError("Gitea update issue response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea update issue response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return issue;
},
@@ -260,7 +291,11 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/issues/${index}/comments?page=${page}&limit=${limit}`,
);
if (!comments) {
- throw new GiteaApiError("Gitea comments response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea comments response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return comments;
},
@@ -281,7 +316,11 @@ export function createGiteaClient(
},
);
if (!comment) {
- throw new GiteaApiError("Gitea create comment response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea create comment response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return comment;
},
@@ -296,7 +335,11 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/labels`,
);
if (!labels) {
- throw new GiteaApiError("Gitea labels response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea labels response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return labels;
},
@@ -320,7 +363,11 @@ export function createGiteaClient(
},
);
if (!label) {
- throw new GiteaApiError("Gitea create label response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea create label response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return label;
},
@@ -387,7 +434,11 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/issues/${index}`,
);
if (!issue) {
- throw new GiteaApiError("Gitea issue response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea issue response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return issue;
},
@@ -404,7 +455,11 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/issues?state=${state}&page=${page}&limit=100`,
);
if (!issues) {
- throw new GiteaApiError("Gitea issues response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea issues response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return issues;
},
@@ -420,7 +475,11 @@ export function createGiteaClient(
`${owner(repositoryOwner, repositoryName)}/pulls?state=open&page=${page}&limit=100`,
);
if (!pulls) {
- throw new GiteaApiError("Gitea pull requests response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea pull requests response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return pulls;
},
@@ -434,7 +493,11 @@ export async function verifyGiteaToken(baseUrl: string, token: string) {
"/user",
);
if (!user) {
- throw new GiteaApiError("Gitea user response was empty", 500);
+ throw new GiteaApiError(
+ "Gitea user response was empty",
+ 500,
+ "EMPTY_RESPONSE",
+ );
}
return user;
}
diff --git a/apps/web/src/components/project/gitea-integration-settings.tsx b/apps/web/src/components/project/gitea-integration-settings.tsx
index 230303e20..7488c5858 100644
--- a/apps/web/src/components/project/gitea-integration-settings.tsx
+++ b/apps/web/src/components/project/gitea-integration-settings.tsx
@@ -194,7 +194,11 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {
if (showToast) {
if (result.isInstalled && result.hasRequiredPermissions) {
toast.success(t("settings:giteaIntegration.toast.verifyOk"));
- } else if (!result.repositoryExists) {
+ } else if (result.failureReason === "redirected") {
+ toast.error(t("settings:giteaIntegration.toast.redirected"));
+ } else if (result.failureReason === "not_a_gitea_instance") {
+ toast.error(t("settings:giteaIntegration.toast.notGiteaInstance"));
+ } else if (result.failureReason === "repository_not_found") {
toast.error(t("settings:giteaIntegration.toast.repoNotFound"));
} else {
toast.warning(t("settings:giteaIntegration.toast.verifyWarning"));
@@ -819,18 +823,18 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {
verificationResult.result.isInstalled &&
verificationResult.result.hasRequiredPermissions
? "border-success/25 bg-success/10"
- : verificationResult.result.repositoryExists
- ? "border-warning/25 bg-warning/10"
- : "border-destructive/25 bg-destructive/10",
+ : verificationResult.result.failureReason
+ ? "border-destructive/25 bg-destructive/10"
+ : "border-warning/25 bg-warning/10",
)}
>
{verificationResult.result.isInstalled &&
verificationResult.result.hasRequiredPermissions ? (
<CheckCircle className="mt-0.5 h-4 w-4 flex-shrink-0 text-success-foreground" />
- ) : verificationResult.result.repositoryExists ? (
- <AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0 text-warning-foreground" />
- ) : (
+ ) : verificationResult.result.failureReason ? (
<XCircle className="mt-0.5 h-4 w-4 flex-shrink-0 text-destructive-foreground" />
+ ) : (
+ <AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0 text-warning-foreground" />
)}
<div className="flex-1">
<p className="font-medium">
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index 3818e6b94..9204b3cc9 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Aufgabenlink-Kommentare bei neuen Issues sind deaktiviert",
"settingsUpdateError": "Gitea-Integration konnte nicht aktualisiert werden",
"secretCopied": "Kopiert",
- "unableToCopySecret": "Geheimnis konnte nicht kopiert werden"
+ "unableToCopySecret": "Geheimnis konnte nicht kopiert werden",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Anzeigen",
"webhookHide": "Ausblenden",
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index 44297cd50..5cb747f6a 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Τα σχόλια με σύνδεσμο εργασίας στα νέα issues είναι απενεργοποιημένα",
"settingsUpdateError": "Αποτυχία ενημέρωσης ενσωμάτωσης Gitea",
"secretCopied": "Copied",
- "unableToCopySecret": "Δεν ήταν δυνατή η αντιγραφή του μυστικού"
+ "unableToCopySecret": "Δεν ήταν δυνατή η αντιγραφή του μυστικού",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Show",
"webhookHide": "Hide",
diff --git a/i18n/en-US.json b/i18n/en-US.json
index f80ce52a9..eadd54aff 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -930,6 +930,8 @@
"verifyOk": "Gitea token can access this repository",
"verifyWarning": "Check token permissions or repository access",
"repoNotFound": "Repository not found or not accessible",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly.",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
"verifyError": "Failed to verify Gitea access",
"tokenRequired": "Personal access token is required",
"tokenRequiredVerify": "Enter a token to verify",
diff --git a/i18n/es-ES.json b/i18n/es-ES.json
index df6dbcc4d..e837f0cde 100644
--- a/i18n/es-ES.json
+++ b/i18n/es-ES.json
@@ -1129,7 +1129,9 @@
"commentOnDisabled": "Los comentarios con enlace a la tarea en nuevas issues están desactivados",
"settingsUpdateError": "Error al actualizar la integración con Gitea",
"secretCopied": "Copiado",
- "unableToCopySecret": "No se pudo copiar el secreto"
+ "unableToCopySecret": "No se pudo copiar el secreto",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Mostrar",
"webhookHide": "Ocultar",
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index 4383c4339..7b567a7e0 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Les commentaires de lien de tâche sur les nouvelles issues sont désactivés",
"settingsUpdateError": "Échec de la mise à jour de l'intégration Gitea",
"secretCopied": "Copied",
- "unableToCopySecret": "Impossible de copier le secret"
+ "unableToCopySecret": "Impossible de copier le secret",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Show",
"webhookHide": "Hide",
diff --git a/i18n/hi-IN.json b/i18n/hi-IN.json
index 07dda8e87..e7203e0cb 100644
--- a/i18n/hi-IN.json
+++ b/i18n/hi-IN.json
@@ -944,7 +944,9 @@
"commentOnDisabled": "नई issues पर कार्य लिंक टिप्पणियाँ बंद हैं",
"settingsUpdateError": "Gitea एकीकरण अपडेट करने में विफल",
"secretCopied": "कॉपी किया",
- "unableToCopySecret": "सीक्रेट कॉपी करने में असमर्थ"
+ "unableToCopySecret": "सीक्रेट कॉपी करने में असमर्थ",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "दिखाएँ",
"webhookHide": "छिपाएँ",
@@ -1490,7 +1492,8 @@
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"table": {
"addColumnBefore": "बाईं ओर कॉलम जोड़ें",
@@ -1500,6 +1503,9 @@
"addRowAfter": "नीचे पंक्ति जोड़ें",
"deleteRow": "पंक्ति हटाएँ",
"deleteTable": "तालिका हटाएँ"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
}
@@ -1616,7 +1622,8 @@
"terraform": "Terraform",
"typescript": "TypeScript",
"xml": "XML",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"embed": {
"choice": {
@@ -1632,6 +1639,9 @@
"onlyYoutube": "केवल YouTube लिंक एम्बेड किए जा सकते हैं।"
},
"onlyYoutubeInline": "केवल YouTube URL एम्बेड किए जा सकते हैं। इसके बजाय लिंक मोड का उपयोग करें।"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
},
diff --git a/i18n/id-ID.json b/i18n/id-ID.json
index da4a29b82..81353a20b 100644
--- a/i18n/id-ID.json
+++ b/i18n/id-ID.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Komentar tautan tugas pada issue baru dimatikan",
"settingsUpdateError": "Gagal memperbarui integrasi Gitea",
"secretCopied": "Disalin",
- "unableToCopySecret": "Tidak dapat menyalin rahasia"
+ "unableToCopySecret": "Tidak dapat menyalin rahasia",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Tampilkan",
"webhookHide": "Sembunyikan",
diff --git a/i18n/it-IT.json b/i18n/it-IT.json
index c1616ebce..2589d2b2b 100644
--- a/i18n/it-IT.json
+++ b/i18n/it-IT.json
@@ -944,7 +944,9 @@
"commentOnDisabled": "Commenti con link alle attività sulle nuove issue sono disattivati",
"settingsUpdateError": "Aggiornamento integrazione Gitea fallito",
"secretCopied": "Copiato",
- "unableToCopySecret": "Impossibile copiare il segreto"
+ "unableToCopySecret": "Impossibile copiare il segreto",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Mostra",
"webhookHide": "Nascondi",
@@ -1490,7 +1492,8 @@
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"table": {
"addColumnBefore": "Inserisci colonna a sinistra",
@@ -1500,6 +1503,9 @@
"addRowAfter": "Inserisci riga sotto",
"deleteRow": "Elimina riga",
"deleteTable": "Elimina tabella"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
}
@@ -1616,7 +1622,8 @@
"terraform": "Terraform",
"typescript": "TypeScript",
"xml": "XML",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"embed": {
"choice": {
@@ -1632,6 +1639,9 @@
"onlyYoutube": "Solo i link YouTube possono essere incorporati."
},
"onlyYoutubeInline": "Solo gli URL YouTube possono essere incorporati. Usa invece la modalità link."
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
},
diff --git a/i18n/ko-KR.json b/i18n/ko-KR.json
index 4ef06dc83..388299ae3 100644
--- a/i18n/ko-KR.json
+++ b/i18n/ko-KR.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "새 이슈의 작업 링크 댓글이 꺼져 있습니다",
"settingsUpdateError": "Gitea 연동 업데이트에 실패했습니다",
"secretCopied": "복사됨",
- "unableToCopySecret": "시크릿을 복사할 수 없습니다"
+ "unableToCopySecret": "시크릿을 복사할 수 없습니다",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "표시",
"webhookHide": "숨기기",
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index 5de790883..718ae47a9 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Коментарите со линк до задачата на новите issues се исклучени",
"settingsUpdateError": "Неуспешно ажурирање на Gitea интеграцијата",
"secretCopied": "Copied",
- "unableToCopySecret": "Не можеше да се копира тајната"
+ "unableToCopySecret": "Не можеше да се копира тајната",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Show",
"webhookHide": "Hide",
diff --git a/i18n/nl-NL.json b/i18n/nl-NL.json
index e7e10e996..47b72e0bb 100644
--- a/i18n/nl-NL.json
+++ b/i18n/nl-NL.json
@@ -1129,7 +1129,9 @@
"commentOnDisabled": "Reacties met taaklinks op nieuwe issues staan uit",
"settingsUpdateError": "Bijwerken Gitea-integratie mislukt",
"secretCopied": "Gekopieerd",
- "unableToCopySecret": "Kopiëren van geheim mislukt"
+ "unableToCopySecret": "Kopiëren van geheim mislukt",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Tonen",
"webhookHide": "Verbergen",
diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json
index d88989273..6d1e50082 100644
--- a/i18n/pt-BR.json
+++ b/i18n/pt-BR.json
@@ -944,7 +944,9 @@
"commentOnDisabled": "Os comentários com link da tarefa em novas issues estão desativados",
"settingsUpdateError": "Falha ao atualizar a integração com o Gitea",
"secretCopied": "Copiado",
- "unableToCopySecret": "Não foi possível copiar o segredo"
+ "unableToCopySecret": "Não foi possível copiar o segredo",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Mostrar",
"webhookHide": "Ocultar",
@@ -1490,7 +1492,8 @@
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"table": {
"addColumnBefore": "Inserir coluna à esquerda",
@@ -1500,6 +1503,9 @@
"addRowAfter": "Inserir linha abaixo",
"deleteRow": "Excluir linha",
"deleteTable": "Excluir tabela"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
}
@@ -1616,7 +1622,8 @@
"terraform": "Terraform",
"typescript": "TypeScript",
"xml": "XML",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"embed": {
"choice": {
@@ -1632,6 +1639,9 @@
"onlyYoutube": "Somente links do YouTube podem ser incorporados."
},
"onlyYoutubeInline": "Somente URLs do YouTube podem ser incorporadas. Use o modo de link."
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
},
diff --git a/i18n/ru-RU.json b/i18n/ru-RU.json
index 337023a8e..394ab9929 100644
--- a/i18n/ru-RU.json
+++ b/i18n/ru-RU.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Комментарии со ссылками на задачи в новых issues отключены",
"settingsUpdateError": "Не удалось обновить интеграцию с Gitea",
"secretCopied": "Скопировано",
- "unableToCopySecret": "Не удалось скопировать секрет"
+ "unableToCopySecret": "Не удалось скопировать секрет",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Показать",
"webhookHide": "Скрыть",
diff --git a/i18n/tr-TR.json b/i18n/tr-TR.json
index dcd89f9ea..b5db61d9d 100644
--- a/i18n/tr-TR.json
+++ b/i18n/tr-TR.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Yeni sorunlardaki talep bağlantısı yorumları kapatıldı",
"settingsUpdateError": "Gitea entegrasyonu güncellenemedi",
"secretCopied": "Kopyalandı",
- "unableToCopySecret": "Gizli anahtar kopyalanamıyor"
+ "unableToCopySecret": "Gizli anahtar kopyalanamıyor",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Göster",
"webhookHide": "Gizle",
diff --git a/i18n/uk-UA.json b/i18n/uk-UA.json
index 5d14c6252..c63ff5b7d 100644
--- a/i18n/uk-UA.json
+++ b/i18n/uk-UA.json
@@ -782,7 +782,9 @@
"commentOnDisabled": "Коментарі з посиланнями на завдання в нових issues вимкнено",
"settingsUpdateError": "Не вдалося оновити інтеґрацію з Gitea",
"secretCopied": "Скопійовано",
- "unableToCopySecret": "Не вдалося скопіювати секрет"
+ "unableToCopySecret": "Не вдалося скопіювати секрет",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Показати",
"webhookHide": "Сховати",
diff --git a/i18n/vi-VN.json b/i18n/vi-VN.json
index 6e4faac5c..4105aba25 100644
--- a/i18n/vi-VN.json
+++ b/i18n/vi-VN.json
@@ -944,7 +944,9 @@
"commentOnDisabled": "Đã tắt bình luận liên kết công việc trên issue mới",
"settingsUpdateError": "Không thể cập nhật tích hợp Gitea",
"secretCopied": "Đã sao chép",
- "unableToCopySecret": "Không thể sao chép khóa bí mật"
+ "unableToCopySecret": "Không thể sao chép khóa bí mật",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "Hiện",
"webhookHide": "Ẩn",
@@ -1490,7 +1492,8 @@
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"table": {
"addColumnBefore": "Chèn cột bên trái",
@@ -1500,6 +1503,9 @@
"addRowAfter": "Chèn hàng phía dưới",
"deleteRow": "Xóa hàng",
"deleteTable": "Xóa bảng"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
}
@@ -1616,7 +1622,8 @@
"terraform": "Terraform",
"typescript": "TypeScript",
"xml": "XML",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"embed": {
"choice": {
@@ -1632,6 +1639,9 @@
"onlyYoutube": "Chỉ có thể nhúng liên kết YouTube."
},
"onlyYoutubeInline": "Chỉ có thể nhúng URL YouTube. Hãy dùng chế độ liên kết thay thế."
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
},
diff --git a/i18n/zh-CN.json b/i18n/zh-CN.json
index c431ad908..6a6af3b3e 100644
--- a/i18n/zh-CN.json
+++ b/i18n/zh-CN.json
@@ -944,7 +944,9 @@
"commentOnDisabled": "新 Issue 的任务链接评论已关闭",
"settingsUpdateError": "更新 Gitea 集成失败",
"secretCopied": "已复制",
- "unableToCopySecret": "无法复制密钥"
+ "unableToCopySecret": "无法复制密钥",
+ "notGiteaInstance": "The URL does not point to a Gitea instance",
+ "redirected": "Gitea URL redirected (usually to HTTPS). Use the final URL directly."
},
"webhookShow": "显示",
"webhookHide": "隐藏",
@@ -1490,7 +1492,8 @@
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"table": {
"addColumnBefore": "在左侧插入列",
@@ -1500,6 +1503,9 @@
"addRowAfter": "在下方插入行",
"deleteRow": "删除行",
"deleteTable": "删除表格"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
}
@@ -1616,7 +1622,8 @@
"terraform": "Terraform",
"typescript": "TypeScript",
"xml": "XML",
- "yaml": "YAML"
+ "yaml": "YAML",
+ "mermaid": "Mermaid"
},
"embed": {
"choice": {
@@ -1632,6 +1639,9 @@
"onlyYoutube": "只能嵌入 YouTube 链接。"
},
"onlyYoutubeInline": "仅支持嵌入 YouTube URL,请改用链接模式。"
+ },
+ "mermaid": {
+ "renderFailed": "Mermaid diagram couldn't be rendered"
}
}
},
diff --git a/tests/api-integration/project-reorder.test.ts b/tests/api-integration/project-reorder.test.ts
index af7fd81ee..71afd8839 100644
--- a/tests/api-integration/project-reorder.test.ts
+++ b/tests/api-integration/project-reorder.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
-import { schema } from "../../apps/api/src/database";
+import type { schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
import { mockAuthenticatedSession } from "./helpers/auth";
import { resetTestDatabase } from "./helpers/database";
diff --git a/tests/api/gitea-integration/verify-gitea-access-fetch.test.ts b/tests/api/gitea-integration/verify-gitea-access-fetch.test.ts
new file mode 100644
index 000000000..b25171939
--- /dev/null
+++ b/tests/api/gitea-integration/verify-gitea-access-fetch.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { default: verifyGiteaAccess } = await import(
+ "../../../apps/api/src/gitea-integration/controllers/verify-gitea-access"
+);
+
+// ponytail: capture the env var so we don't leak the SSRF bypass across tests.
+const originalAllowPrivate =
+ process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS;
+
+function makeResponse(status: number, body: string | object = ""): Response {
+ const text = typeof body === "string" ? body : JSON.stringify(body);
+ return new Response(text, {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+beforeEach(() => {
+ // Bypass the SSRF DNS check so the test does not depend on outbound DNS
+ // resolving gitea.example. Without this, the real lookup would fail in CI.
+ process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS = "true";
+});
+
+afterEach(() => {
+ if (originalAllowPrivate === undefined) {
+ delete process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS;
+ } else {
+ process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS = originalAllowPrivate;
+ }
+ vi.unstubAllGlobals();
+});
+
+describe("verifyGiteaAccess — fetch integration", () => {
+ it("returns success when the API returns a user and a writable repo", async () => {
+ const fetchMock = vi.fn();
+ fetchMock
+ .mockResolvedValueOnce(makeResponse(200, { id: 1, login: "owner" }))
+ .mockResolvedValueOnce(
+ makeResponse(200, {
+ name: "repo",
+ owner: { login: "owner" },
+ html_url: "https://gitea.example/owner/repo",
+ private: false,
+ permissions: { admin: true, push: true, pull: true },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result).toEqual({
+ isInstalled: true,
+ hasRequiredPermissions: true,
+ repositoryExists: true,
+ repositoryPrivate: false,
+ missingPermissions: [],
+ message: "Token can access the repository.",
+ failureReason: null,
+ });
+ });
+
+ it("returns the 'not a Gitea instance' message when the response body is HTML, not JSON", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(makeResponse(200, "<html>Not Gitea</html>"));
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.repositoryExists).toBe(false);
+ expect(result.failureReason).toBe("not_a_gitea_instance");
+ expect(result.message).toBe("The URL does not point to a Gitea instance.");
+ });
+
+ it("returns a redirect-specific message when the API responds with 308", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(makeResponse(308, ""));
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "http://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.failureReason).toBe("redirected");
+ expect(result.message).toContain("redirected");
+ expect(result.message).toContain("HTTP 308");
+ });
+
+ it("returns a redirect-specific message when the API responds with 301", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(makeResponse(301, ""));
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "http://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.failureReason).toBe("redirected");
+ expect(result.message).toContain("HTTP 301");
+ });
+
+ it("returns the repository-not-found message when getRepo responds with 404", async () => {
+ const fetchMock = vi.fn();
+ fetchMock
+ .mockResolvedValueOnce(makeResponse(200, { id: 1, login: "owner" }))
+ .mockResolvedValueOnce(makeResponse(404, "Not Found"));
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.failureReason).toBe("repository_not_found");
+ expect(result.message).toBe(
+ "Repository not found or not accessible with this token.",
+ );
+ });
+
+ it("returns the repository-not-found message when /user responds with 404", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(makeResponse(404, "Not Found"));
+ vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.failureReason).toBe("repository_not_found");
+ expect(result.message).toBe(
+ "Repository not found or not accessible with this token.",
+ );
+ });
+});
diff --git a/tests/api/gitea-integration/verify-gitea-access.test.ts b/tests/api/gitea-integration/verify-gitea-access.test.ts
new file mode 100644
index 000000000..d7ef279a0
--- /dev/null
+++ b/tests/api/gitea-integration/verify-gitea-access.test.ts
@@ -0,0 +1,155 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { mockGiteaFetch } = vi.hoisted(() => ({
+ mockGiteaFetch: vi.fn(),
+}));
+
+// Stub GiteaApiError locally; the controller branches on `instanceof` + `.kind`.
+type GiteaApiErrorKind =
+ | "REDIRECT"
+ | "INVALID_JSON"
+ | "HTTP_ERROR"
+ | "TIMEOUT"
+ | "EMPTY_RESPONSE";
+
+class GiteaApiError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public kind: GiteaApiErrorKind,
+ public body?: string,
+ ) {
+ super(message);
+ this.name = "GiteaApiError";
+ }
+}
+
+vi.mock("../../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({
+ GiteaApiError,
+ giteaFetch: (...args: unknown[]) => mockGiteaFetch(...args),
+ createGiteaClient: () => ({
+ getRepo: (...args: unknown[]) => mockGiteaFetch(...args),
+ }),
+ verifyGiteaToken: (...args: unknown[]) => mockGiteaFetch(...args),
+}));
+
+const { default: verifyGiteaAccess } = await import(
+ "../../../apps/api/src/gitea-integration/controllers/verify-gitea-access"
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("verifyGiteaAccess", () => {
+ it("returns success when the token can access the repository", async () => {
+ mockGiteaFetch
+ .mockResolvedValueOnce({ id: 1, login: "owner" })
+ .mockResolvedValueOnce({
+ name: "repo",
+ owner: { login: "owner" },
+ html_url: "https://gitea.example/owner/repo",
+ private: false,
+ permissions: { admin: true, push: true, pull: true },
+ });
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result).toMatchObject({
+ isInstalled: true,
+ hasRequiredPermissions: true,
+ repositoryExists: true,
+ repositoryPrivate: false,
+ missingPermissions: [],
+ message: "Token can access the repository.",
+ failureReason: null,
+ });
+ });
+
+ it("returns a redirect-specific message when the URL redirects (e.g. http → https)", async () => {
+ mockGiteaFetch.mockRejectedValue(
+ new GiteaApiError(
+ "Gitea request was redirected (HTTP 308)",
+ 308,
+ "REDIRECT",
+ ),
+ );
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "http://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.repositoryExists).toBe(false);
+ expect(result.failureReason).toBe("redirected");
+ expect(result.message).toContain("redirected");
+ expect(result.message).toContain("HTTP 308");
+ expect(result.message).not.toContain("does not point to a Gitea instance.");
+ });
+
+ it("returns a redirect-specific message when getRepo redirects after the token check succeeds", async () => {
+ mockGiteaFetch
+ .mockResolvedValueOnce({ id: 1, login: "owner" })
+ .mockRejectedValueOnce(
+ new GiteaApiError(
+ "Gitea request was redirected (HTTP 301)",
+ 301,
+ "REDIRECT",
+ ),
+ );
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "http://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.failureReason).toBe("redirected");
+ expect(result.message).toContain("HTTP 301");
+ });
+
+ it("returns 'not a Gitea instance' when the response is invalid JSON", async () => {
+ mockGiteaFetch.mockRejectedValue(
+ new GiteaApiError("Gitea API returned invalid JSON", 200, "INVALID_JSON"),
+ );
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "https://not-gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.isInstalled).toBe(false);
+ expect(result.failureReason).toBe("not_a_gitea_instance");
+ expect(result.message).toBe("The URL does not point to a Gitea instance.");
+ });
+
+ it("does not branch on the message string — INVALID_JSON must use the kind discriminator", async () => {
+ // Same status and message as the redirect case, but with INVALID_JSON kind.
+ // The controller must dispatch on kind, not message substring matching.
+ mockGiteaFetch.mockRejectedValue(
+ new GiteaApiError("Gitea request was redirected", 308, "INVALID_JSON"),
+ );
+
+ const result = await verifyGiteaAccess({
+ baseUrl: "http://gitea.example",
+ accessToken: "token",
+ repositoryOwner: "owner",
+ repositoryName: "repo",
+ });
+
+ expect(result.failureReason).toBe("not_a_gitea_instance");
+ expect(result.message).toBe("The URL does not point to a Gitea instance.");
+ });
+});