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.

feat(api): add Gitea integration REST API

Tin17782774d8f0
diff --git a/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
new file mode 100644
index 000000000..d7b61df2f
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/create-gitea-integration.ts
@@ -0,0 +1,169 @@
+import { randomBytes } from "node:crypto";
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { integrationTable, projectTable } from "../../database/schema";
+import {
+ type GiteaConfig,
+ getDefaultGiteaConfig,
+ normalizeGiteaBaseUrl,
+ validateGiteaConfig,
+} from "../../plugins/gitea/config";
+import {
+ createGiteaClient,
+ verifyGiteaToken,
+} from "../../plugins/gitea/utils/gitea-api";
+
+async function createGiteaIntegration({
+ projectId,
+ baseUrl,
+ accessToken,
+ repositoryOwner,
+ repositoryName,
+}: {
+ projectId: string;
+ baseUrl: string;
+ accessToken: string | undefined;
+ repositoryOwner: string;
+ repositoryName: string;
+}) {
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+
+ if (!project) {
+ throw new HTTPException(404, { message: "Project not found" });
+ }
+
+ const normalizedBase = normalizeGiteaBaseUrl(baseUrl);
+
+ const existingIntegration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ });
+
+ let resolvedToken = accessToken?.trim() ?? "";
+ if (!resolvedToken && existingIntegration) {
+ const prev = JSON.parse(existingIntegration.config) as GiteaConfig;
+ resolvedToken = prev.accessToken;
+ }
+
+ if (!resolvedToken) {
+ throw new HTTPException(400, {
+ message: "Personal access token is required",
+ });
+ }
+
+ await verifyGiteaToken(normalizedBase, resolvedToken);
+
+ const client = createGiteaClient({
+ baseUrl: normalizedBase,
+ accessToken: resolvedToken,
+ });
+ await client.getRepo(repositoryOwner, repositoryName);
+
+ const allGitea = await db.query.integrationTable.findMany({
+ where: eq(integrationTable.type, "gitea"),
+ });
+
+ for (const integration of allGitea) {
+ if (integration.projectId === projectId) {
+ continue;
+ }
+ try {
+ const cfg = JSON.parse(integration.config) as {
+ baseUrl?: string;
+ repositoryOwner?: string;
+ repositoryName?: string;
+ };
+ if (
+ normalizeGiteaBaseUrl(cfg.baseUrl ?? "") === normalizedBase &&
+ cfg.repositoryOwner === repositoryOwner &&
+ cfg.repositoryName === repositoryName
+ ) {
+ throw new HTTPException(409, {
+ message: `Repository ${repositoryOwner}/${repositoryName} on this Gitea instance is already linked to another project`,
+ });
+ }
+ } catch (error) {
+ if (error instanceof HTTPException) {
+ throw error;
+ }
+ }
+ }
+
+ const webhookSecret = existingIntegration
+ ? ((JSON.parse(existingIntegration.config) as GiteaConfig).webhookSecret ??
+ randomBytes(24).toString("hex"))
+ : randomBytes(24).toString("hex");
+
+ const config: GiteaConfig = getDefaultGiteaConfig(
+ normalizedBase,
+ resolvedToken,
+ repositoryOwner,
+ repositoryName,
+ webhookSecret,
+ );
+
+ const validation = await validateGiteaConfig(config);
+ if (!validation.valid) {
+ throw new HTTPException(400, {
+ message: validation.errors?.join(", ") ?? "Invalid config",
+ });
+ }
+
+ if (existingIntegration) {
+ const [updated] = await db
+ .update(integrationTable)
+ .set({
+ config: JSON.stringify(config),
+ isActive: true,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ )
+ .returning();
+
+ return {
+ id: updated?.id,
+ projectId: updated?.projectId,
+ baseUrl: normalizedBase,
+ repositoryOwner,
+ repositoryName,
+ webhookSecret,
+ isActive: updated?.isActive,
+ createdAt: updated?.createdAt,
+ updatedAt: updated?.updatedAt,
+ };
+ }
+
+ const [newIntegration] = await db
+ .insert(integrationTable)
+ .values({
+ projectId,
+ type: "gitea",
+ config: JSON.stringify(config),
+ isActive: true,
+ })
+ .returning();
+
+ return {
+ id: newIntegration?.id,
+ projectId: newIntegration?.projectId,
+ baseUrl: normalizedBase,
+ repositoryOwner,
+ repositoryName,
+ webhookSecret,
+ isActive: newIntegration?.isActive,
+ createdAt: newIntegration?.createdAt,
+ updatedAt: newIntegration?.updatedAt,
+ };
+}
+
+export default createGiteaIntegration;
diff --git a/apps/api/src/gitea-integration/controllers/delete-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/delete-gitea-integration.ts
new file mode 100644
index 000000000..f07b3162e
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/delete-gitea-integration.ts
@@ -0,0 +1,30 @@
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { integrationTable } from "../../database/schema";
+
+async function deleteGiteaIntegration(projectId: string) {
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ });
+
+ if (!integration) {
+ throw new HTTPException(404, { message: "Gitea integration not found" });
+ }
+
+ await db
+ .delete(integrationTable)
+ .where(
+ and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ );
+
+ return { success: true, message: "Gitea integration deleted" };
+}
+
+export default deleteGiteaIntegration;
diff --git a/apps/api/src/gitea-integration/controllers/get-gitea-integration.ts b/apps/api/src/gitea-integration/controllers/get-gitea-integration.ts
new file mode 100644
index 000000000..81376aebf
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/get-gitea-integration.ts
@@ -0,0 +1,49 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../database";
+import { integrationTable } from "../../database/schema";
+import {
+ defaultGiteaConfig,
+ type GiteaConfig,
+} from "../../plugins/gitea/config";
+
+function maskToken(token: string): string {
+ if (token.length <= 8) {
+ return "••••••••";
+ }
+ return `${token.slice(0, 4)}••••••${token.slice(-4)}`;
+}
+
+async function getGiteaIntegration(projectId: string) {
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ });
+
+ if (!integration) {
+ return null;
+ }
+
+ const config = JSON.parse(integration.config) as GiteaConfig;
+
+ const apiBase = process.env.KANEO_API_URL || "http://localhost:1337";
+
+ return {
+ id: integration.id,
+ projectId: integration.projectId,
+ baseUrl: config.baseUrl,
+ repositoryOwner: config.repositoryOwner,
+ repositoryName: config.repositoryName,
+ maskedAccessToken: maskToken(config.accessToken),
+ webhookUrl: `${apiBase.replace(/\/$/, "")}/api/gitea-integration/webhook/${integration.id}`,
+ webhookSecret: config.webhookSecret ?? "",
+ branchPattern: config.branchPattern || defaultGiteaConfig.branchPattern,
+ commentTaskLinkOnGiteaIssue: config.commentTaskLinkOnGiteaIssue !== false,
+ isActive: integration.isActive,
+ createdAt: integration.createdAt,
+ updatedAt: integration.updatedAt,
+ };
+}
+
+export default getGiteaIntegration;
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
new file mode 100644
index 000000000..5f6f1cc80
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts
@@ -0,0 +1,439 @@
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ activityTable,
+ integrationTable,
+ labelTable,
+ projectTable,
+ taskTable,
+} from "../../database/schema";
+import type { GiteaConfig } from "../../plugins/gitea/config";
+import { extractTaskNumberGitea } from "../../plugins/gitea/utils/branch-matcher";
+import {
+ createGiteaClient,
+ type GiteaIssue,
+} from "../../plugins/gitea/utils/gitea-api";
+import {
+ createExternalLink,
+ findExternalLink,
+} from "../../plugins/github/services/link-manager";
+import { findTaskByNumber } from "../../plugins/github/services/task-service";
+import {
+ extractIssuePriority,
+ 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;
+ updated: number;
+ skipped: number;
+ errors?: string[];
+};
+
+export async function importGiteaIssues(
+ projectId: string,
+): Promise<ImportResult> {
+ const errors: string[] = [];
+ let imported = 0;
+ let updated = 0;
+ let skipped = 0;
+
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+
+ if (!project) {
+ throw new HTTPException(404, { message: "Project not found" });
+ }
+
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ });
+
+ if (!integration) {
+ throw new HTTPException(404, { message: "Gitea integration not found" });
+ }
+
+ if (!integration.isActive) {
+ throw new HTTPException(400, {
+ message: "Gitea integration is not active",
+ });
+ }
+
+ const config = JSON.parse(integration.config) as GiteaConfig;
+
+ if (!config.accessToken || !config.baseUrl) {
+ throw new HTTPException(400, {
+ message: "Gitea access token or base URL not configured",
+ });
+ }
+
+ const client = createGiteaClient(config);
+
+ const allIssues: GiteaIssue[] = [];
+ let page = 1;
+
+ while (true) {
+ const issues = await client.listIssues(
+ config.repositoryOwner,
+ config.repositoryName,
+ page,
+ "open",
+ );
+
+ if (issues.length === 0) break;
+
+ const issuesOnly = issues.filter((issue) => !issue.pull_request);
+ allIssues.push(...issuesOnly);
+
+ if (issues.length < 100) break;
+ page++;
+ }
+
+ for (const issue of allIssues) {
+ try {
+ const result = await importSingleIssue(
+ issue,
+ integration.id,
+ projectId,
+ project.workspaceId,
+ config,
+ client,
+ );
+
+ if (result === "imported") {
+ imported++;
+ } else if (result === "updated") {
+ updated++;
+ } else {
+ skipped++;
+ }
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+ errors.push(`Issue #${issue.number}: ${errorMessage}`);
+ }
+ }
+
+ 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;
+ }> = [];
+ page = 1;
+
+ while (true) {
+ const pulls = await client.listPulls(
+ config.repositoryOwner,
+ config.repositoryName,
+ page,
+ );
+
+ if (pulls.length === 0) break;
+
+ allPRs.push(...pulls);
+
+ if (pulls.length < 100) break;
+ page++;
+ }
+
+ for (const pr of allPRs) {
+ try {
+ if (!pr.head?.ref) {
+ continue;
+ }
+ await linkPullRequestToTask(
+ {
+ ...pr,
+ head: { ref: pr.head.ref },
+ },
+ integration.id,
+ projectId,
+ project.slug,
+ config,
+ );
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+ errors.push(`PR #${pr.number}: ${errorMessage}`);
+ }
+ }
+
+ return {
+ imported,
+ updated,
+ skipped,
+ ...(errors.length > 0 ? { errors } : {}),
+ };
+}
+
+async function importSingleIssue(
+ issue: GiteaIssue,
+ integrationId: string,
+ projectId: string,
+ workspaceId: string,
+ config: GiteaConfig,
+ client: ReturnType<typeof createGiteaClient>,
+): Promise<"imported" | "updated" | "skipped"> {
+ const existingLink = await findExternalLink(
+ integrationId,
+ "issue",
+ issue.number.toString(),
+ );
+
+ const labels = issue.labels ?? [];
+ const priority = extractIssuePriority(labels as never);
+ const status = extractIssueStatus(labels as never);
+
+ if (existingLink) {
+ const updateData: Record<string, unknown> = {
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.body),
+ };
+
+ if (priority) updateData.priority = priority;
+ if (status) updateData.status = status;
+
+ await db
+ .update(taskTable)
+ .set(updateData)
+ .where(eq(taskTable.id, existingLink.taskId));
+
+ await importLabelsForTask(labels, existingLink.taskId, workspaceId);
+
+ await importCommentsForTask(
+ issue.number,
+ existingLink.taskId,
+ config,
+ client,
+ );
+
+ return "updated";
+ }
+
+ const nextTaskNumber = await getNextTaskNumber(projectId);
+
+ 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,
+ };
+
+ const [createdTask] = await db
+ .insert(taskTable)
+ .values(taskValues)
+ .returning();
+
+ if (!createdTask) {
+ throw new Error("Failed to create task");
+ }
+
+ await createExternalLink({
+ taskId: createdTask.id,
+ integrationId,
+ resourceType: "issue",
+ externalId: issue.number.toString(),
+ url: issue.html_url,
+ title: issue.title,
+ metadata: {
+ state: issue.state,
+ createdFrom: "gitea-import",
+ author: issue.user?.login ?? issue.user?.username,
+ },
+ });
+
+ await importLabelsForTask(labels, createdTask.id, workspaceId);
+
+ await importCommentsForTask(issue.number, createdTask.id, config, client);
+
+ return "imported";
+}
+
+async function importLabelsForTask(
+ issueLabels: GiteaIssue["labels"],
+ taskId: string,
+ workspaceId: string,
+): Promise<void> {
+ const nonSystemLabels = (issueLabels ?? [])
+ .map((label) => {
+ if (typeof label === "string") {
+ return { name: label, color: "#6B7280" };
+ }
+ return {
+ name: label.name,
+ color: label.color
+ ? `#${String(label.color).replace(/^#/, "")}`
+ : "#6B7280",
+ };
+ })
+ .filter(
+ (label) =>
+ label.name &&
+ !label.name.startsWith("priority:") &&
+ !label.name.startsWith("status:"),
+ ) as Array<{ name: string; color: string }>;
+
+ for (const labelData of nonSystemLabels) {
+ const existingLabelOnTask = await db.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.taskId, taskId),
+ eq(labelTable.name, labelData.name),
+ ),
+ });
+
+ if (existingLabelOnTask) {
+ continue;
+ }
+
+ const existingWorkspaceLabel = await db.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.workspaceId, workspaceId),
+ eq(labelTable.name, labelData.name),
+ ),
+ });
+
+ const colorToUse = existingWorkspaceLabel?.color || labelData.color;
+
+ await db.insert(labelTable).values({
+ name: labelData.name,
+ color: colorToUse,
+ taskId,
+ workspaceId,
+ });
+ }
+}
+
+async function importCommentsForTask(
+ issueNumber: number,
+ taskId: string,
+ config: GiteaConfig,
+ client: ReturnType<typeof createGiteaClient>,
+): Promise<void> {
+ const allComments: Array<{
+ body: string;
+ html_url: string;
+ user?: { login?: string; username?: string; avatar_url?: string } | null;
+ }> = [];
+ let page = 1;
+
+ while (true) {
+ const comments = await client.listIssueComments(
+ config.repositoryOwner,
+ config.repositoryName,
+ issueNumber,
+ page,
+ 100,
+ );
+
+ if (comments.length === 0) break;
+
+ allComments.push(...comments);
+
+ if (comments.length < 100) break;
+ page++;
+ }
+
+ const existingActivities = await db.query.activityTable.findMany({
+ where: and(
+ eq(activityTable.taskId, taskId),
+ eq(activityTable.externalSource, "gitea"),
+ ),
+ });
+
+ const existingExternalUrls = new Set(
+ existingActivities.filter((a) => a.externalUrl).map((a) => a.externalUrl),
+ );
+
+ for (const comment of allComments) {
+ const username = comment.user?.login ?? comment.user?.username ?? "";
+ if (username.endsWith("[bot]")) {
+ continue;
+ }
+
+ if (existingExternalUrls.has(comment.html_url)) {
+ continue;
+ }
+
+ await db.insert(activityTable).values({
+ taskId,
+ type: "comment",
+ content: comment.body,
+ externalUserName: username || "Unknown",
+ externalUserAvatar: comment.user?.avatar_url ?? null,
+ externalSource: "gitea",
+ externalUrl: comment.html_url,
+ });
+ }
+}
+
+async function linkPullRequestToTask(
+ pr: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ state: string;
+ head: { ref: string };
+ user?: { login?: string; username?: string; avatar_url?: string } | null;
+ },
+ integrationId: string,
+ projectId: string,
+ projectSlug: string,
+ config: GiteaConfig,
+): Promise<void> {
+ const taskNumber = extractTaskNumberGitea(
+ pr.head.ref,
+ pr.title,
+ pr.body ?? undefined,
+ config,
+ projectSlug,
+ );
+
+ if (!taskNumber) {
+ return;
+ }
+
+ const task = await findTaskByNumber(projectId, taskNumber);
+
+ if (!task) {
+ return;
+ }
+
+ const existingLink = await findExternalLink(
+ integrationId,
+ "pull_request",
+ pr.number.toString(),
+ );
+
+ if (existingLink) {
+ return;
+ }
+
+ await createExternalLink({
+ taskId: task.id,
+ integrationId,
+ resourceType: "pull_request",
+ externalId: pr.number.toString(),
+ url: pr.html_url,
+ title: pr.title,
+ metadata: {
+ state: pr.state,
+ branch: pr.head.ref,
+ author: pr.user?.login ?? pr.user?.username,
+ },
+ });
+}
diff --git a/apps/api/src/gitea-integration/controllers/list-gitea-repositories.ts b/apps/api/src/gitea-integration/controllers/list-gitea-repositories.ts
new file mode 100644
index 000000000..16782845b
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/list-gitea-repositories.ts
@@ -0,0 +1,66 @@
+import { HTTPException } from "hono/http-exception";
+import { normalizeGiteaBaseUrl } from "../../plugins/gitea/config";
+import {
+ createGiteaClient,
+ verifyGiteaToken,
+} from "../../plugins/gitea/utils/gitea-api";
+
+type RepoRow = {
+ id: number;
+ name: string;
+ full_name: string;
+ private: boolean;
+ owner: { login: string };
+ html_url: string;
+};
+
+async function listGiteaRepositories({
+ baseUrl,
+ accessToken,
+}: {
+ baseUrl: string;
+ accessToken: string;
+}): Promise<{ repositories: RepoRow[] }> {
+ const normalized = normalizeGiteaBaseUrl(baseUrl);
+
+ try {
+ await verifyGiteaToken(normalized, accessToken);
+ } catch {
+ throw new HTTPException(401, {
+ message: "Invalid Gitea token or could not reach instance.",
+ });
+ }
+
+ const client = createGiteaClient({
+ baseUrl: normalized,
+ accessToken,
+ });
+
+ const all: RepoRow[] = [];
+ let page = 1;
+
+ while (true) {
+ const batch = await client.listUserRepos(page, 50);
+ if (!batch.length) break;
+
+ for (const repo of batch) {
+ const ownerLogin = repo.owner?.login ?? repo.owner?.username ?? "";
+ all.push({
+ id: repo.id,
+ name: repo.name,
+ full_name: repo.full_name,
+ private: repo.private,
+ owner: { login: ownerLogin },
+ html_url: repo.html_url,
+ });
+ }
+
+ if (batch.length < 50) break;
+ page += 1;
+ if (page > 50) break;
+ }
+
+ return { repositories: all };
+}
+
+export default listGiteaRepositories;
diff --git a/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts b/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
new file mode 100644
index 000000000..b7c0b127e
--- /dev/null
+++ b/apps/api/src/gitea-integration/controllers/verify-gitea-access.ts
@@ -0,0 +1,75 @@
+import { HTTPException } from "hono/http-exception";
+import { normalizeGiteaBaseUrl } from "../../plugins/gitea/config";
+import {
+ createGiteaClient,
+ verifyGiteaToken,
+} from "../../plugins/gitea/utils/gitea-api";
+
+async function verifyGiteaAccess({
+ baseUrl,
+ accessToken,
+ repositoryOwner,
+ repositoryName,
+}: {
+ baseUrl: string;
+ accessToken: string;
+ repositoryOwner: string;
+ repositoryName: string;
+}) {
+ try {
+ const normalized = normalizeGiteaBaseUrl(baseUrl);
+ await verifyGiteaToken(normalized, accessToken);
+
+ const client = createGiteaClient({
+ baseUrl: normalized,
+ accessToken,
+ });
+
+ 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);
+
+ return {
+ isInstalled: true,
+ hasRequiredPermissions: Boolean(hasIssuesWrite),
+ repositoryExists: true,
+ repositoryPrivate: repo.private,
+ missingPermissions: hasIssuesWrite ? [] : ["issues (write)"],
+ message: hasIssuesWrite
+ ? "Token can access the repository."
+ : "Token may not have sufficient permissions to manage issues.",
+ };
+ } catch (error) {
+ const err = error as { status?: number; message?: string };
+
+ if (err.status === 404) {
+ return {
+ isInstalled: false,
+ hasRequiredPermissions: false,
+ repositoryExists: false,
+ repositoryPrivate: null,
+ missingPermissions: [] as string[],
+ message: "Repository not found or not accessible with this token.",
+ };
+ }
+
+ if (err.status === 401) {
+ throw new HTTPException(401, {
+ message: "Invalid Gitea token or unauthorized.",
+ });
+ }
+
+ throw new HTTPException(500, {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Failed to verify Gitea access",
+ });
+ }
+}
+
+export default verifyGiteaAccess;
diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.ts
new file mode 100644
index 000000000..47b8a9469
--- /dev/null
+++ b/apps/api/src/gitea-integration/index.ts
@@ -0,0 +1,401 @@
+import { and, eq } from "drizzle-orm";
+import type { Context } from "hono";
+import { Hono } from "hono";
+import { HTTPException } from "hono/http-exception";
+import { describeRoute, resolver, validator } from "hono-openapi";
+import * as v from "valibot";
+import db from "../database";
+import { integrationTable, projectTable } from "../database/schema";
+import { type GiteaConfig, validateGiteaConfig } from "../plugins/gitea/config";
+import { handleGiteaWebhookRequest } from "../plugins/gitea/webhook-handler";
+import { giteaIntegrationSchema } from "../schemas";
+import { validateWorkspaceAccess } from "../utils/validate-workspace-access";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+import createGiteaIntegration from "./controllers/create-gitea-integration";
+import deleteGiteaIntegration from "./controllers/delete-gitea-integration";
+import getGiteaIntegration from "./controllers/get-gitea-integration";
+import { importGiteaIssues } from "./controllers/import-gitea-issues";
+import listGiteaRepositories from "./controllers/list-gitea-repositories";
+import verifyGiteaAccess from "./controllers/verify-gitea-access";
+
+const giteaRepositorySchema = v.object({
+ id: v.number(),
+ name: v.string(),
+ full_name: v.string(),
+ owner: v.object({
+ login: v.string(),
+ }),
+ private: v.boolean(),
+ html_url: v.string(),
+});
+
+const verificationResultSchema = v.object({
+ isInstalled: v.boolean(),
+ hasRequiredPermissions: v.boolean(),
+ repositoryExists: v.boolean(),
+ repositoryPrivate: v.nullable(v.boolean()),
+ missingPermissions: v.array(v.string()),
+ message: v.string(),
+});
+
+const importResultSchema = v.object({
+ imported: v.number(),
+ updated: v.number(),
+ skipped: v.number(),
+ errors: v.optional(v.array(v.string())),
+});
+
+const giteaIntegration = new Hono<{
+ Variables: {
+ userId: string;
+ workspaceId: string;
+ apiKey?: {
+ id: string;
+ userId: string;
+ enabled: boolean;
+ };
+ };
+}>()
+ .post(
+ "/repositories",
+ describeRoute({
+ operationId: "listGiteaRepositories",
+ tags: ["Gitea"],
+ description: "List repositories accessible with a Gitea token",
+ responses: {
+ 200: {
+ description: "Repositories",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.object({
+ repositories: v.array(giteaRepositorySchema),
+ }),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ baseUrl: v.pipe(v.string(), v.minLength(1)),
+ accessToken: v.pipe(v.string(), v.minLength(1)),
+ }),
+ ),
+ async (c) => {
+ const { baseUrl, accessToken } = c.req.valid("json");
+ const result = await listGiteaRepositories({ baseUrl, accessToken });
+ return c.json(result);
+ },
+ )
+ .post(
+ "/verify",
+ describeRoute({
+ operationId: "verifyGiteaAccess",
+ tags: ["Gitea"],
+ description: "Verify Gitea token and repository access",
+ responses: {
+ 200: {
+ description: "Verification result",
+ content: {
+ "application/json": {
+ schema: resolver(verificationResultSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ baseUrl: v.pipe(v.string(), v.minLength(1)),
+ accessToken: v.pipe(v.string(), v.minLength(1)),
+ repositoryOwner: v.pipe(v.string(), v.minLength(1)),
+ repositoryName: v.pipe(v.string(), v.minLength(1)),
+ }),
+ ),
+ async (c) => {
+ const body = c.req.valid("json");
+ const result = await verifyGiteaAccess(body);
+ return c.json(result);
+ },
+ )
+ .get(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "getGiteaIntegration",
+ tags: ["Gitea"],
+ description: "Get Gitea integration for a project",
+ responses: {
+ 200: {
+ description: "Gitea integration details",
+ content: {
+ "application/json": {
+ schema: resolver(giteaIntegrationSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const integration = await getGiteaIntegration(projectId);
+ if (!integration) {
+ return c.json(null, 200);
+ }
+ return c.json(integration);
+ },
+ )
+ .post(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "createGiteaIntegration",
+ tags: ["Gitea"],
+ description: "Create or update Gitea integration for a project",
+ responses: {
+ 200: {
+ description: "Integration saved",
+ content: {
+ "application/json": {
+ schema: resolver(giteaIntegrationSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ validator(
+ "json",
+ v.object({
+ baseUrl: v.pipe(v.string(), v.minLength(1)),
+ accessToken: v.optional(v.string()),
+ repositoryOwner: v.pipe(v.string(), v.minLength(1)),
+ repositoryName: v.pipe(v.string(), v.minLength(1)),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const body = c.req.valid("json");
+ await createGiteaIntegration({
+ projectId,
+ baseUrl: body.baseUrl,
+ accessToken: body.accessToken,
+ repositoryOwner: body.repositoryOwner,
+ repositoryName: body.repositoryName,
+ });
+ const integration = await getGiteaIntegration(projectId);
+ if (!integration) {
+ throw new HTTPException(500, { message: "Failed to load integration" });
+ }
+ return c.json(integration);
+ },
+ )
+ .patch(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "updateGiteaIntegration",
+ tags: ["Gitea"],
+ description: "Update Gitea integration settings",
+ responses: {
+ 200: {
+ description: "Updated",
+ content: {
+ "application/json": {
+ schema: resolver(giteaIntegrationSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ validator(
+ "json",
+ v.object({
+ isActive: v.optional(v.boolean()),
+ commentTaskLinkOnGiteaIssue: v.optional(v.boolean()),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const body = c.req.valid("json");
+
+ const row = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ });
+
+ if (!row) {
+ return c.json({ error: "Integration not found" }, 404);
+ }
+
+ let config: GiteaConfig;
+ try {
+ config = JSON.parse(row.config) as GiteaConfig;
+ } catch {
+ throw new HTTPException(500, { message: "Invalid integration config" });
+ }
+
+ if (body.commentTaskLinkOnGiteaIssue !== undefined) {
+ config = {
+ ...config,
+ commentTaskLinkOnGiteaIssue: body.commentTaskLinkOnGiteaIssue,
+ };
+ }
+
+ const validation = await validateGiteaConfig(config);
+ if (!validation.valid) {
+ throw new HTTPException(400, {
+ message: validation.errors?.join(", ") ?? "Invalid config",
+ });
+ }
+
+ await db
+ .update(integrationTable)
+ .set({
+ config: JSON.stringify(config),
+ isActive:
+ body.isActive !== undefined
+ ? body.isActive
+ : (row.isActive ?? true),
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitea"),
+ ),
+ );
+
+ const updated = await getGiteaIntegration(projectId);
+ if (!updated) {
+ throw new HTTPException(500, { message: "Failed to load integration" });
+ }
+ return c.json(updated, 200);
+ },
+ )
+ .delete(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "deleteGiteaIntegration",
+ tags: ["Gitea"],
+ description: "Delete Gitea integration for a project",
+ responses: {
+ 200: {
+ description: "Deleted",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.object({
+ success: v.boolean(),
+ message: v.string(),
+ }),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const result = await deleteGiteaIntegration(projectId);
+ return c.json(result);
+ },
+ )
+ .post(
+ "/import-issues",
+ describeRoute({
+ operationId: "importGiteaIssues",
+ tags: ["Gitea"],
+ description: "Import Gitea issues as tasks",
+ responses: {
+ 200: {
+ description: "Import result",
+ content: {
+ "application/json": {
+ schema: resolver(importResultSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ projectId: v.string(),
+ }),
+ ),
+ async (c, next) => {
+ const userId = c.get("userId");
+ if (!userId) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+
+ const { projectId } = c.req.valid("json");
+
+ const [project] = await db
+ .select({ workspaceId: projectTable.workspaceId })
+ .from(projectTable)
+ .where(eq(projectTable.id, projectId))
+ .limit(1);
+
+ if (!project) {
+ throw new HTTPException(404, { message: "Project not found" });
+ }
+
+ const apiKey = c.get("apiKey");
+ const apiKeyId = apiKey?.id;
+
+ await validateWorkspaceAccess(userId, project.workspaceId, apiKeyId);
+ c.set("workspaceId", project.workspaceId);
+
+ return next();
+ },
+ async (c) => {
+ const { projectId } = c.req.valid("json");
+ const result = await importGiteaIssues(projectId);
+ return c.json(result);
+ },
+ );
+
+export async function handleGiteaWebhookRoute(c: Context) {
+ const integrationId = c.req.param("integrationId");
+ if (!integrationId) {
+ return c.json({ error: "Missing integration id" }, 400);
+ }
+
+ const arrayBuffer = await c.req.arrayBuffer();
+ const body = Buffer.from(arrayBuffer).toString("utf8");
+
+ const signature =
+ c.req.header("x-gitea-signature") || c.req.header("X-Gitea-Signature");
+
+ const eventName =
+ c.req.header("x-gitea-event") ||
+ c.req.header("X-Gitea-Event") ||
+ c.req.header("x-github-event");
+
+ const result = await handleGiteaWebhookRequest(
+ integrationId,
+ body,
+ signature,
+ eventName,
+ );
+
+ if (!result.success) {
+ return c.json({ error: result.error }, 400);
+ }
+
+ return c.json({ status: "success" });
+}
+
+export default giteaIntegration;