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(api): harden Gitea import, API client, and webhooks

Tin229a4bb1ec48
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 9fd9611ee..5a4dac43c 100644
--- a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
+++ b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
@@ -105,7 +105,6 @@ async function createGiteaIntegration({
error,
},
);
- throw error;
}
}
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 58e4799fc..2fcc26611 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, inArray, notInArray } from "drizzle-orm";
+import { and, eq, inArray, max, notInArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@ -27,7 +27,6 @@ import {
extractIssueStatus,
} from "../../plugins/github/utils/extract-priority";
import { formatTaskDescriptionFromIssue } from "../../plugins/github/utils/format";
-import getNextTaskNumber from "../../task/controllers/get-next-task-number";
type ImportResult = {
imported: number;
@@ -75,7 +74,19 @@ export async function importGiteaIssues(
});
}
- const config = JSON.parse(integration.config) as GiteaConfig;
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(integration.config) as GiteaConfig;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn("Invalid Gitea integration config JSON", {
+ integrationId: integration.id,
+ error,
+ });
+ throw new HTTPException(400, {
+ message: `Invalid Gitea integration config: ${message}`,
+ });
+ }
if (!config.accessToken || !config.baseUrl) {
throw new HTTPException(400, {
@@ -223,26 +234,42 @@ async function importSingleIssue(
return "updated";
}
- const nextTaskNumber = await getNextTaskNumber(projectId);
+ const createdTask = await db.transaction(async (tx) => {
+ const [lockedProject] = await tx
+ .select()
+ .from(projectTable)
+ .where(eq(projectTable.id, projectId))
+ .for("update");
- const taskValues: typeof taskTable.$inferInsert = {
- projectId,
- userId: null,
- title: issue.title,
- description: formatTaskDescriptionFromIssue(issue.body),
- status: status || "to-do",
- priority: priority || null,
- number: nextTaskNumber + 1,
- };
+ if (!lockedProject) {
+ throw new Error("Project not found");
+ }
- const [createdTask] = await db
- .insert(taskTable)
- .values(taskValues)
- .returning();
+ const [result] = await tx
+ .select({ maxNumber: max(taskTable.number) })
+ .from(taskTable)
+ .where(eq(taskTable.projectId, projectId));
- if (!createdTask) {
- throw new Error("Failed to create task");
- }
+ const nextNumber = (result?.maxNumber ?? 0) + 1;
+
+ const taskValues: typeof taskTable.$inferInsert = {
+ projectId,
+ userId: null,
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.body),
+ status: status || "to-do",
+ priority: priority || null,
+ number: nextNumber,
+ };
+
+ const [created] = await tx.insert(taskTable).values(taskValues).returning();
+
+ if (!created) {
+ throw new Error("Failed to create task");
+ }
+
+ return created;
+ });
await createExternalLink({
taskId: createdTask.id,
@@ -343,12 +370,17 @@ async function importLabelsForTask(
const colorToUse = existingWorkspaceLabel?.color || labelData.color;
- await db.insert(labelTable).values({
- name: labelData.name,
- color: colorToUse,
- taskId,
- workspaceId,
- });
+ await db
+ .insert(labelTable)
+ .values({
+ name: labelData.name,
+ color: colorToUse,
+ taskId,
+ workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
}
}
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 bbe952718..9ad354010 100644
--- a/apps/api/src/plugins/gitea/events/task-description-changed.ts
+++ b/apps/api/src/plugins/gitea/events/task-description-changed.ts
@@ -76,7 +76,7 @@ export async function handleTaskDescriptionChanged(
Date.now() - new Date(lastDescSync.timestamp).getTime();
if (
timeSinceLastSync < 2000 &&
- lastDescSync.source !== "kaneo" &&
+ lastDescSync.source === "gitea" &&
newDescNormalized === lastDescSync.value
) {
console.log(
diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.ts
index ac49d5f66..9441fd7f9 100644
--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts
+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts
@@ -57,6 +57,8 @@ function authHeaders(token: string): HeadersInit {
};
}
+const GITEA_FETCH_TIMEOUT_MS = 10_000;
+
export async function giteaFetch<T>(
baseUrl: string,
token: string,
@@ -65,13 +67,43 @@ export async function giteaFetch<T>(
): Promise<T | undefined> {
const root = normalizeGiteaBaseUrl(baseUrl);
const url = `${root}/api/v1${path.startsWith("/") ? path : `/${path}`}`;
- const res = await fetch(url, {
- ...init,
- headers: {
- ...authHeaders(token),
- ...init?.headers,
- },
- });
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(
+ () => controller.abort(),
+ GITEA_FETCH_TIMEOUT_MS,
+ );
+ if (init?.signal) {
+ if (init.signal.aborted) {
+ controller.abort();
+ } else {
+ init.signal.addEventListener("abort", () => controller.abort(), {
+ once: true,
+ });
+ }
+ }
+
+ let res: Response;
+ try {
+ res = await fetch(url, {
+ ...init,
+ signal: controller.signal,
+ headers: {
+ ...authHeaders(token),
+ ...init?.headers,
+ },
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new GiteaApiError(
+ `Gitea request timed out after ${GITEA_FETCH_TIMEOUT_MS}ms`,
+ 408,
+ );
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
const text = await res.text();
if (!res.ok) {
@@ -279,15 +311,15 @@ export function createGiteaClient(
labelIds: number[],
) {
if (labelIds.length === 0) return;
- await giteaFetch<unknown>(
- baseUrl,
- accessToken,
- `${owner(repositoryOwner, repositoryName)}/issues/${index}/labels`,
- {
+ const MAX_LABELS_PER_REQUEST = 50;
+ const path = `${owner(repositoryOwner, repositoryName)}/issues/${index}/labels`;
+ for (let i = 0; i < labelIds.length; i += MAX_LABELS_PER_REQUEST) {
+ const chunk = labelIds.slice(i, i + MAX_LABELS_PER_REQUEST);
+ await giteaFetch<unknown>(baseUrl, accessToken, path, {
method: "POST",
- body: JSON.stringify(labelIds),
- },
- );
+ body: JSON.stringify(chunk),
+ });
+ }
},
async replaceIssueLabels(
diff --git a/apps/api/src/plugins/gitea/utils/labels.ts b/apps/api/src/plugins/gitea/utils/labels.ts
index 135ce9e68..d369fed86 100644
--- a/apps/api/src/plugins/gitea/utils/labels.ts
+++ b/apps/api/src/plugins/gitea/utils/labels.ts
@@ -18,39 +18,45 @@ function getLabelColor(labelName: string): string {
return labelColors[labelName] || "6B7280";
}
-async function getOrCreateLabelId(
- client: ReturnType<typeof createGiteaClient>,
- config: Pick<GiteaConfig, "repositoryOwner" | "repositoryName">,
- name: string,
-): Promise<number> {
- const { repositoryOwner, repositoryName } = config;
- const labels = await client.listLabels(repositoryOwner, repositoryName);
-
- const found = labels.find((l) => l.name === name);
- if (found) {
- return found.id;
- }
-
- const color = getLabelColor(name);
- const created = await client.createLabel(
- repositoryOwner,
- repositoryName,
- name,
- color,
- );
- return created.id;
-}
-
export async function ensureLabelsExistGitea(
config: GiteaConfig,
labels: string[],
): Promise<Map<string, number>> {
const client = createGiteaClient(config);
const map = new Map<string, number>();
+ const { repositoryOwner, repositoryName } = config;
+
+ let existingLabels: GiteaLabel[];
+ try {
+ existingLabels = await client.listLabels(repositoryOwner, repositoryName);
+ } catch (error) {
+ console.error("Failed to list Gitea labels for ensureLabelsExistGitea", {
+ repositoryOwner,
+ repositoryName,
+ error,
+ });
+ return map;
+ }
+
+ const nameToId = new Map(existingLabels.map((l) => [l.name, l.id]));
+
for (const name of labels) {
try {
- const id = await getOrCreateLabelId(client, config, name);
- map.set(name, id);
+ const existingId = nameToId.get(name);
+ if (existingId !== undefined) {
+ map.set(name, existingId);
+ continue;
+ }
+
+ const color = getLabelColor(name);
+ const created = await client.createLabel(
+ repositoryOwner,
+ repositoryName,
+ name,
+ color,
+ );
+ nameToId.set(name, created.id);
+ map.set(name, created.id);
} catch (error) {
console.error(`Failed to ensure Gitea label "${name}":`, error);
}
@@ -65,14 +71,12 @@ export async function addLabelsToIssueGitea(
) {
if (labelNames.length === 0) return;
- const client = createGiteaClient(config);
+ const nameToId = await ensureLabelsExistGitea(config, labelNames);
const ids: number[] = [];
for (const name of labelNames) {
- try {
- const id = await getOrCreateLabelId(client, config, name);
+ const id = nameToId.get(name);
+ if (id !== undefined) {
ids.push(id);
- } catch (error) {
- console.error(`Failed to add Gitea label "${name}":`, error);
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
index a48937f7e..d00f67f32 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts
@@ -43,59 +43,66 @@ export async function handleGiteaIssueReopened(payload: IssueReopenedPayload) {
);
for (const integration of integrations) {
- const externalLink = await db.query.externalLinkTable.findFirst({
- where: and(
- eq(externalLinkTable.integrationId, integration.id),
- eq(externalLinkTable.resourceType, "issue"),
- eq(externalLinkTable.externalId, issue.number.toString()),
- ),
- });
+ try {
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "issue"),
+ eq(externalLinkTable.externalId, issue.number.toString()),
+ ),
+ });
- if (!externalLink) {
- continue;
- }
+ if (!externalLink) {
+ continue;
+ }
- const task = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, externalLink.taskId),
- });
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
- if (!task) {
- continue;
- }
+ if (!task) {
+ continue;
+ }
- let existingMetadata: Record<string, unknown> = {};
- if (externalLink.metadata) {
- try {
- existingMetadata = JSON.parse(externalLink.metadata) as Record<
- string,
- unknown
- >;
- } catch (error) {
- console.warn("Failed to parse Gitea issue metadata for reopen sync", {
- externalLinkId: externalLink.id,
- metadata: externalLink.metadata,
- error,
- });
+ let existingMetadata: Record<string, unknown> = {};
+ if (externalLink.metadata) {
+ try {
+ existingMetadata = JSON.parse(externalLink.metadata) as Record<
+ string,
+ unknown
+ >;
+ } catch (error) {
+ console.warn("Failed to parse Gitea issue metadata for reopen sync", {
+ externalLinkId: externalLink.id,
+ metadata: externalLink.metadata,
+ error,
+ });
+ }
}
- }
- if (existingMetadata.createdFrom === "kaneo") {
- continue;
- }
+ if (existingMetadata.createdFrom === "kaneo") {
+ continue;
+ }
- const targetStatus = await resolveTargetStatus(
- task.projectId,
- "issue_reopened",
- "to-do",
- );
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_reopened",
+ "to-do",
+ );
- await updateTaskStatus(task.id, targetStatus);
+ await updateTaskStatus(task.id, targetStatus);
- await updateExternalLink(externalLink.id, {
- metadata: {
- ...existingMetadata,
- state: "open",
- },
- });
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: "open",
+ },
+ });
+ } catch (error) {
+ console.error("Gitea issue_reopened handler failed for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ }
}
}
diff --git a/apps/api/src/plugins/gitea/webhooks/label-created.ts b/apps/api/src/plugins/gitea/webhooks/label-created.ts
index 6395ca215..77ac34c67 100644
--- a/apps/api/src/plugins/gitea/webhooks/label-created.ts
+++ b/apps/api/src/plugins/gitea/webhooks/label-created.ts
@@ -1,6 +1,6 @@
-import { eq } from "drizzle-orm";
+import { sql } from "drizzle-orm";
import db from "../../../database";
-import { labelTable, projectTable } from "../../../database/schema";
+import { labelTable } from "../../../database/schema";
import {
findAllIntegrationsByGiteaRepo,
repoOwnerLogin,
@@ -45,11 +45,8 @@ export async function handleGiteaLabelCreated(payload: LabelCreatePayload) {
continue;
}
- const project = await db.query.projectTable.findFirst({
- where: eq(projectTable.id, integration.project.id),
- });
-
- if (!project?.workspaceId) {
+ const workspaceId = integration.project.workspaceId;
+ if (!workspaceId) {
continue;
}
@@ -60,8 +57,11 @@ export async function handleGiteaLabelCreated(payload: LabelCreatePayload) {
.values({
name: label.name,
color,
- workspaceId: project.workspaceId,
+ workspaceId,
})
- .onConflictDoNothing();
+ .onConflictDoNothing({
+ target: [labelTable.workspaceId, labelTable.name],
+ where: sql`${labelTable.taskId} is null`,
+ });
}
}