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-api): harden webhook and sync handling

Tin265555a5e71b
diff --git a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
index d7b61df2f..a4fcc868c 100644
--- a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
+++ b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
@@ -130,16 +130,22 @@ async function createGiteaIntegration({
)
.returning();
+ if (!updated) {
+ throw new HTTPException(500, {
+ message: "Failed to update Gitea integration",
+ });
+ }
+
return {
- id: updated?.id,
- projectId: updated?.projectId,
+ id: updated.id,
+ projectId: updated.projectId,
baseUrl: normalizedBase,
repositoryOwner,
repositoryName,
webhookSecret,
- isActive: updated?.isActive,
- createdAt: updated?.createdAt,
- updatedAt: updated?.updatedAt,
+ isActive: updated.isActive,
+ createdAt: updated.createdAt,
+ updatedAt: updated.updatedAt,
};
}
@@ -153,16 +159,22 @@ async function createGiteaIntegration({
})
.returning();
+ if (!newIntegration) {
+ throw new HTTPException(500, {
+ message: "Failed to create Gitea integration",
+ });
+ }
+
return {
- id: newIntegration?.id,
- projectId: newIntegration?.projectId,
+ id: newIntegration.id,
+ projectId: newIntegration.projectId,
baseUrl: normalizedBase,
repositoryOwner,
repositoryName,
webhookSecret,
- isActive: newIntegration?.isActive,
- createdAt: newIntegration?.createdAt,
- updatedAt: newIntegration?.updatedAt,
+ isActive: newIntegration.isActive,
+ createdAt: newIntegration.createdAt,
+ updatedAt: newIntegration.updatedAt,
};
}
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
index 5f6f1cc80..2055746b6 100644
--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
@@ -1,4 +1,4 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, inArray, notInArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@ -13,6 +13,7 @@ import { extractTaskNumberGitea } from "../../plugins/gitea/utils/branch-matcher
import {
createGiteaClient,
type GiteaIssue,
+ type GiteaPullRequest,
} from "../../plugins/gitea/utils/gitea-api";
import {
createExternalLink,
@@ -121,15 +122,7 @@ export async function importGiteaIssues(
}
}
- const allPRs: Array<{
- number: number;
- title: string;
- body: string | null;
- html_url: string;
- state: string;
- head: { ref: string };
- user?: { login?: string; username?: string; avatar_url?: string } | null;
- }> = [];
+ const allPRs: GiteaPullRequest[] = [];
page = 1;
while (true) {
@@ -287,13 +280,35 @@ async function importLabelsForTask(
!label.name.startsWith("status:"),
) as Array<{ name: string; color: string }>;
+ const expectedNames = nonSystemLabels.map((label) => label.name);
+
+ if (expectedNames.length > 0) {
+ await db
+ .delete(labelTable)
+ .where(
+ and(
+ eq(labelTable.taskId, taskId),
+ notInArray(labelTable.name, expectedNames),
+ ),
+ );
+ } else {
+ await db.delete(labelTable).where(eq(labelTable.taskId, taskId));
+ }
+
+ const existingLabelsOnTask = await db.query.labelTable.findMany({
+ where:
+ expectedNames.length > 0
+ ? and(
+ eq(labelTable.taskId, taskId),
+ inArray(labelTable.name, expectedNames),
+ )
+ : eq(labelTable.taskId, taskId),
+ });
+
for (const labelData of nonSystemLabels) {
- const existingLabelOnTask = await db.query.labelTable.findFirst({
- where: and(
- eq(labelTable.taskId, taskId),
- eq(labelTable.name, labelData.name),
- ),
- });
+ const existingLabelOnTask = existingLabelsOnTask.find(
+ (label) => label.name === labelData.name,
+ );
if (existingLabelOnTask) {
continue;
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 b7c0b127e..b35102f9b 100644
--- a/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
+++ b/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
@@ -28,10 +28,7 @@ async function verifyGiteaAccess({
const repo = await client.getRepo(repositoryOwner, repositoryName);
const perms = repo.permissions;
- const hasIssuesWrite =
- perms?.admin === true ||
- perms?.push === true ||
- (perms?.pull === true && perms?.push !== false);
+ const hasIssuesWrite = perms?.admin === true || perms?.push === true;
return {
isInstalled: true,
diff --git a/apps/api/src/plugins/gitea/config.ts b/apps/api/src/plugins/gitea/config.ts
index de3ac0192..b0e4ff14d 100644
--- a/apps/api/src/plugins/gitea/config.ts
+++ b/apps/api/src/plugins/gitea/config.ts
@@ -4,10 +4,10 @@ import { branchPatterns } from "../github/config";
export { branchPatterns };
export const giteaConfigSchema = v.object({
- baseUrl: v.string(),
- accessToken: v.string(),
- repositoryOwner: v.string(),
- repositoryName: v.string(),
+ baseUrl: v.pipe(v.string(), v.url()),
+ accessToken: v.pipe(v.string(), v.trim(), v.nonEmpty()),
+ repositoryOwner: v.pipe(v.string(), v.trim(), v.nonEmpty()),
+ repositoryName: v.pipe(v.string(), v.trim(), v.nonEmpty()),
webhookSecret: v.optional(v.string()),
branchPattern: v.optional(v.string()),
customBranchRegex: v.optional(v.string()),
diff --git a/apps/api/src/plugins/gitea/events/task-comment-created.ts b/apps/api/src/plugins/gitea/events/task-comment-created.ts
index 58c5edc8f..01dde456f 100644
--- a/apps/api/src/plugins/gitea/events/task-comment-created.ts
+++ b/apps/api/src/plugins/gitea/events/task-comment-created.ts
@@ -26,7 +26,27 @@ export async function handleTaskCommentCreated(
try {
const client = createGiteaClient(config);
- const issueNumber = Number.parseInt(existingLink.externalId, 10);
+ if (!/^\d+$/.test(existingLink.externalId)) {
+ console.error(
+ "Skipping Gitea comment sync for invalid external issue id",
+ {
+ taskId: event.taskId,
+ externalId: existingLink.externalId,
+ },
+ );
+ return;
+ }
+
+ const issueNumber = Number(existingLink.externalId);
+
+ if (!Number.isFinite(issueNumber) || issueNumber < 1) {
+ console.error("Skipping Gitea comment sync for invalid issue number", {
+ taskId: event.taskId,
+ externalId: existingLink.externalId,
+ issueNumber,
+ });
+ return;
+ }
await client.createIssueComment(
repositoryOwner,
diff --git a/apps/api/src/plugins/gitea/events/task-created.ts b/apps/api/src/plugins/gitea/events/task-created.ts
index 32905548e..d703f42e1 100644
--- a/apps/api/src/plugins/gitea/events/task-created.ts
+++ b/apps/api/src/plugins/gitea/events/task-created.ts
@@ -44,9 +44,6 @@ export async function handleTaskCreated(
},
);
- const labels = getLabelsForIssue(event.priority, event.status);
- await addLabelsToIssueGitea(config, createdIssue.number, labels);
-
await createExternalLink({
taskId: event.taskId,
integrationId: context.integrationId,
@@ -59,6 +56,9 @@ export async function handleTaskCreated(
createdFrom: "kaneo",
},
});
+
+ const labels = getLabelsForIssue(event.priority, event.status);
+ await addLabelsToIssueGitea(config, createdIssue.number, labels);
} catch (error) {
console.error("Failed to create Gitea issue:", error);
}
diff --git a/apps/api/src/plugins/gitea/events/task-description-changed.ts b/apps/api/src/plugins/gitea/events/task-description-changed.ts
index b054506f4..8e01e22b4 100644
--- a/apps/api/src/plugins/gitea/events/task-description-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts
@@ -46,7 +46,11 @@ export async function handleTaskDescriptionChanged(
const timeSinceLastSync =
Date.now() - new Date(lastDescSync.timestamp).getTime();
- if (timeSinceLastSync < 2000) {
+ if (
+ timeSinceLastSync < 2000 &&
+ lastDescSync.source !== "kaneo" &&
+ newDescNormalized === lastDescSync.value
+ ) {
console.log(
`Skipping description sync - recent sync detected (${timeSinceLastSync}ms ago)`,
);
diff --git a/apps/api/src/plugins/gitea/events/task-title-changed.ts b/apps/api/src/plugins/gitea/events/task-title-changed.ts
index 60b4f8276..6b1e7af2f 100644
--- a/apps/api/src/plugins/gitea/events/task-title-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-title-changed.ts
@@ -43,7 +43,7 @@ export async function handleTaskTitleChanged(
const timeSinceLastSync =
Date.now() - new Date(lastTitleSync.timestamp).getTime();
- if (timeSinceLastSync < 2000) {
+ if (lastTitleSync.source === "gitea" && timeSinceLastSync < 2000) {
console.log(
`Skipping title sync - recent sync detected (${timeSinceLastSync}ms ago)`,
);
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
index 346a8994b..4809d4826 100644
--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -85,7 +85,11 @@ export async function giteaFetch<T>(
try {
return JSON.parse(text) as T;
} catch {
- return undefined as T;
+ throw new GiteaApiError(
+ "Gitea API returned invalid JSON",
+ res.status,
+ text,
+ );
}
}
diff --git a/apps/api/src/plugins/gitea/utils/labels.ts b/apps/api/src/plugins/gitea/utils/labels.ts
index 779a985ec..21db069e0 100644
--- a/apps/api/src/plugins/gitea/utils/labels.ts
+++ b/apps/api/src/plugins/gitea/utils/labels.ts
@@ -107,7 +107,14 @@ export async function removeLabelGitea(
config.repositoryOwner,
config.repositoryName,
);
- } catch {
+ } catch (error) {
+ console.error("Failed to list Gitea labels for removal:", {
+ repositoryOwner: config.repositoryOwner,
+ repositoryName: config.repositoryName,
+ issueIndex,
+ labelName,
+ error,
+ });
return;
}
@@ -121,5 +128,14 @@ export async function removeLabelGitea(
issueIndex,
label.id,
);
- } catch {}
+ } catch (error) {
+ console.error("Failed to remove label from Gitea issue:", {
+ repositoryOwner: config.repositoryOwner,
+ repositoryName: config.repositoryName,
+ issueIndex,
+ labelName,
+ labelId: label.id,
+ error,
+ });
+ }
}
diff --git a/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
index 585d8d583..b5fa81a67 100644
--- a/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
+++ b/apps/api/src/plugins/gitea/utils/sync-label-to-gitea.ts
@@ -45,19 +45,24 @@ function toHexColor(color: string): string {
}
async function getGiteaIssueContext(taskId: string) {
- const externalLink = await db.query.externalLinkTable.findFirst({
+ const externalLinks = await db.query.externalLinkTable.findMany({
where: eq(externalLinkTable.taskId, taskId),
with: {
integration: true,
},
});
- if (!externalLink || externalLink.resourceType !== "issue") {
+ const externalLink = externalLinks.find(
+ (link) =>
+ link.resourceType === "issue" && link.integration?.type === "gitea",
+ );
+
+ if (!externalLink) {
return null;
}
const integration = externalLink.integration;
- if (!integration || integration.type !== "gitea") {
+ if (!integration) {
return null;
}
diff --git a/apps/api/src/plugins/gitea/utils/webhook-repo.ts b/apps/api/src/plugins/gitea/utils/webhook-repo.ts
index 971496b73..acf2873e0 100644
--- a/apps/api/src/plugins/gitea/utils/webhook-repo.ts
+++ b/apps/api/src/plugins/gitea/utils/webhook-repo.ts
@@ -3,7 +3,16 @@ import { normalizeGiteaBaseUrl } from "../config";
export function baseUrlFromRepositoryHtmlUrl(htmlUrl: string): string {
try {
const u = new URL(htmlUrl);
- return normalizeGiteaBaseUrl(`${u.protocol}//${u.host}`);
+ const segments = u.pathname.split("/").filter(Boolean);
+ if (segments.length < 2) {
+ return "";
+ }
+
+ const basePathSegments = segments.slice(0, -2);
+ const basePath =
+ basePathSegments.length > 0 ? `/${basePathSegments.join("/")}` : "";
+
+ return normalizeGiteaBaseUrl(`${u.origin}${basePath}`);
} catch {
return "";
}
diff --git a/apps/api/src/plugins/gitea/webhook-handler.ts b/apps/api/src/plugins/gitea/webhook-handler.ts
index bae7fd149..41d18a786 100644
--- a/apps/api/src/plugins/gitea/webhook-handler.ts
+++ b/apps/api/src/plugins/gitea/webhook-handler.ts
@@ -119,7 +119,7 @@ async function dispatchGiteaEvent(
}
return;
}
- case "create": {
+ case "issue_label": {
await handleGiteaLabelCreated(payload as never);
return;
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
index d692728aa..ad9613c4e 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts
@@ -81,7 +81,5 @@ export async function handleGiteaIssueClosed(payload: IssueClosedPayload) {
state: "closed",
},
});
-
- return;
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts
index de1ba63bf..95b7edac6 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts
@@ -1,3 +1,4 @@
+import { and, eq } from "drizzle-orm";
import db from "../../../database";
import { activityTable } from "../../../database/schema";
import { findExternalLink } from "../../github/services/link-manager";
@@ -65,6 +66,32 @@ export async function handleGiteaIssueCommentCreated(
continue;
}
+ const existingActivities = await db.query.activityTable.findMany({
+ where: and(
+ eq(activityTable.taskId, existingLink.taskId),
+ eq(activityTable.externalSource, "gitea"),
+ ),
+ });
+
+ const alreadyExists = existingActivities.some((activity) => {
+ const eventData = activity.eventData;
+ const externalCommentId =
+ typeof eventData === "object" &&
+ eventData &&
+ "externalCommentId" in eventData
+ ? eventData.externalCommentId
+ : undefined;
+
+ return (
+ externalCommentId === comment.id ||
+ activity.externalUrl === comment.html_url
+ );
+ });
+
+ if (alreadyExists) {
+ continue;
+ }
+
await db.insert(activityTable).values({
taskId: existingLink.taskId,
type: "comment",
@@ -73,8 +100,9 @@ export async function handleGiteaIssueCommentCreated(
externalUserAvatar: comment.user?.avatar_url ?? null,
externalSource: "gitea",
externalUrl: comment.html_url,
+ eventData: {
+ externalCommentId: comment.id,
+ },
});
-
- return;
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
index e1dcc3ffb..daf3213ac 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts
@@ -119,6 +119,10 @@ export async function handleGiteaIssueLabeled(payload: IssueLabeledPayload) {
}
if (payload.action === "label_updated") {
+ if (issue.labels === undefined) {
+ continue;
+ }
+
const task = await db.query.taskTable.findFirst({
where: eq(taskTable.id, existingLink.taskId),
with: {
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
index 933ca3c1e..425f45d51 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
@@ -58,7 +58,16 @@ export async function handleGiteaIssueOpened(payload: IssueOpenedPayload) {
}
for (const integration of integrations) {
- const config = JSON.parse(integration.config) as GiteaConfig;
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(integration.config) as GiteaConfig;
+ } catch (error) {
+ console.error("Invalid Gitea config for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
const projectId = integration.projectId;
const priority = extractIssuePriority(issue.labels);
diff --git a/apps/api/src/plugins/gitea/webhooks/label-created.ts b/apps/api/src/plugins/gitea/webhooks/label-created.ts
index 2e846ed7f..8fd7b73fd 100644
--- a/apps/api/src/plugins/gitea/webhooks/label-created.ts
+++ b/apps/api/src/plugins/gitea/webhooks/label-created.ts
@@ -7,7 +7,7 @@ import {
} from "../services/integration-lookup";
import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
-/** Gitea sends `create` events with ref_type `label` for new labels */
+/** Gitea label events include the created label; older payloads may also set ref_type */
type LabelCreatePayload = {
ref?: string;
ref_type?: string;
@@ -24,7 +24,7 @@ type LabelCreatePayload = {
};
export async function handleGiteaLabelCreated(payload: LabelCreatePayload) {
- if (payload.ref_type !== "label" || !payload.label) {
+ if ((payload.ref_type && payload.ref_type !== "label") || !payload.label) {
return;
}
diff --git a/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts
index cb1c557bc..3806150fb 100644
--- a/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts
@@ -56,7 +56,16 @@ export async function handleGiteaPullRequestOpened(payload: PROpenedPayload) {
continue;
}
- const config = JSON.parse(integration.config) as GiteaConfig;
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(integration.config) as GiteaConfig;
+ } catch (error) {
+ console.error("Invalid Gitea config for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
const projectSlug = integration.project.slug;
const branchName = pull_request.head.ref;
diff --git a/apps/api/src/plugins/gitea/webhooks/push.ts b/apps/api/src/plugins/gitea/webhooks/push.ts
index eda61e38f..0aa96385c 100644
--- a/apps/api/src/plugins/gitea/webhooks/push.ts
+++ b/apps/api/src/plugins/gitea/webhooks/push.ts
@@ -11,6 +11,7 @@ import {
} from "../services/integration-lookup";
import { extractTaskNumberFromBranchGitea } from "../utils/branch-matcher";
import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";
type PushPayload = {
ref: string;
@@ -44,7 +45,12 @@ const PROTECTED_BRANCHES = [
export async function handleGiteaPush(payload: PushPayload) {
const { ref, repository } = payload;
- const branchName = ref.replace("refs/heads/", "");
+ if (!ref.startsWith("refs/heads/")) {
+ console.log(`[Gitea Push] Skipping non-branch ref: ${ref}`);
+ return;
+ }
+
+ const branchName = ref.slice("refs/heads/".length);
console.log(`[Gitea Push] Processing branch: ${branchName}`);
if (PROTECTED_BRANCHES.includes(branchName)) {
@@ -52,8 +58,10 @@ export async function handleGiteaPush(payload: PushPayload) {
return;
}
- const baseUrl = new URL(repository.html_url);
- const origin = `${baseUrl.protocol}//${baseUrl.host}`;
+ const origin = baseUrlFromRepositoryHtmlUrl(repository.html_url);
+ if (!origin) {
+ return;
+ }
const owner = repoOwnerLogin(repository);
const integrations = await findAllIntegrationsByGiteaRepo(
origin,
@@ -125,7 +133,5 @@ export async function handleGiteaPush(payload: PushPayload) {
if (task.status !== targetStatus && !isTaskFinal) {
await updateTaskStatus(task.id, targetStatus);
}
-
- return;
}
}