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 GitLab integration rest

zaralX17fe2fac51fe
diff --git a/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts b/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts
new file mode 100644
index 000000000..ea0105797
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/create-gitlab-integration.ts
@@ -0,0 +1,221 @@
+import { randomBytes } from "node:crypto";
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import type { ContentfulStatusCode } from "hono/utils/http-status";
+import db from "../../database";
+import { integrationTable, projectTable } from "../../database/schema";
+import {
+ type GitlabConfig,
+ type GitlabTokenType,
+ getDefaultGitlabConfig,
+ normalizeGitlabBaseUrl,
+ normalizeProjectPath,
+ validateGitlabConfig,
+} from "../../plugins/gitlab/config";
+import {
+ createGitlabClient,
+ GitlabApiError,
+ verifyGitlabToken,
+} from "../../plugins/gitlab/utils/gitlab-api";
+
+async function createGitlabIntegration({
+ projectId,
+ baseUrl,
+ accessToken,
+ tokenType,
+ projectPath,
+}: {
+ projectId: string;
+ baseUrl: string;
+ accessToken: string | undefined;
+ tokenType: GitlabTokenType;
+ projectPath: 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 = normalizeGitlabBaseUrl(baseUrl);
+ const normalizedPath = normalizeProjectPath(projectPath);
+
+ const existingIntegration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitlab"),
+ ),
+ });
+
+ let resolvedToken = accessToken?.trim() ?? "";
+ if (!resolvedToken && existingIntegration) {
+ try {
+ const previous = JSON.parse(existingIntegration.config) as GitlabConfig;
+ resolvedToken = previous.accessToken;
+ } catch (error) {
+ console.warn("Failed to parse existing GitLab integration config", {
+ integrationId: existingIntegration.id,
+ error,
+ });
+ }
+ }
+
+ if (!resolvedToken) {
+ throw new HTTPException(400, {
+ message: "Access token is required",
+ });
+ }
+
+ try {
+ await verifyGitlabToken(normalizedBase, resolvedToken, tokenType);
+
+ const client = createGitlabClient({
+ baseUrl: normalizedBase,
+ accessToken: resolvedToken,
+ tokenType,
+ });
+ await client.getProject(normalizedPath);
+ } catch (error) {
+ if (error instanceof GitlabApiError) {
+ throw new HTTPException((error.status || 400) as ContentfulStatusCode, {
+ message: error.message,
+ });
+ }
+ throw error;
+ }
+
+ const allGitlab = await db.query.integrationTable.findMany({
+ where: eq(integrationTable.type, "gitlab"),
+ });
+
+ for (const integration of allGitlab) {
+ if (integration.projectId === projectId || !integration.isActive) {
+ continue;
+ }
+ try {
+ const config = JSON.parse(integration.config) as {
+ baseUrl?: string;
+ projectPath?: string;
+ };
+ if (
+ normalizeGitlabBaseUrl(config.baseUrl ?? "") === normalizedBase &&
+ normalizeProjectPath(config.projectPath ?? "") === normalizedPath
+ ) {
+ throw new HTTPException(409, {
+ message: `Project ${normalizedPath} on this GitLab instance is already linked to another project`,
+ });
+ }
+ } catch (error) {
+ if (error instanceof HTTPException) {
+ throw error;
+ }
+ console.warn(
+ "Skipping invalid GitLab integration config during conflict check",
+ {
+ integrationId: integration.id,
+ error,
+ },
+ );
+ }
+ }
+
+ let webhookSecret = randomBytes(24).toString("hex");
+ if (existingIntegration) {
+ try {
+ const previousConfig = JSON.parse(
+ existingIntegration.config,
+ ) as GitlabConfig;
+ webhookSecret = previousConfig.webhookSecret ?? webhookSecret;
+ } catch (error) {
+ console.warn(
+ "Failed to parse existing GitLab config for webhook secret",
+ {
+ integrationId: existingIntegration.id,
+ error,
+ },
+ );
+ }
+ }
+
+ const config = getDefaultGitlabConfig(
+ normalizedBase,
+ resolvedToken,
+ tokenType,
+ normalizedPath,
+ webhookSecret,
+ );
+
+ const validation = await validateGitlabConfig(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, "gitlab"),
+ ),
+ )
+ .returning();
+
+ if (!updated) {
+ throw new HTTPException(500, {
+ message: "Failed to update GitLab integration",
+ });
+ }
+
+ return {
+ id: updated.id,
+ projectId: updated.projectId,
+ baseUrl: normalizedBase,
+ projectPath: normalizedPath,
+ tokenType,
+ webhookSecret,
+ isActive: updated.isActive,
+ createdAt: updated.createdAt,
+ updatedAt: updated.updatedAt,
+ };
+ }
+
+ const [newIntegration] = await db
+ .insert(integrationTable)
+ .values({
+ projectId,
+ type: "gitlab",
+ config: JSON.stringify(config),
+ isActive: true,
+ })
+ .returning();
+
+ if (!newIntegration) {
+ throw new HTTPException(500, {
+ message: "Failed to create GitLab integration",
+ });
+ }
+
+ return {
+ id: newIntegration.id,
+ projectId: newIntegration.projectId,
+ baseUrl: normalizedBase,
+ projectPath: normalizedPath,
+ tokenType,
+ webhookSecret,
+ isActive: newIntegration.isActive,
+ createdAt: newIntegration.createdAt,
+ updatedAt: newIntegration.updatedAt,
+ };
+}
+
+export default createGitlabIntegration;
diff --git a/apps/api/src/gitlab-integration/controllers/delete-gitlab-integration.ts b/apps/api/src/gitlab-integration/controllers/delete-gitlab-integration.ts
new file mode 100644
index 000000000..f3079a2d4
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/delete-gitlab-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 deleteGitlabIntegration(projectId: string) {
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitlab"),
+ ),
+ });
+
+ if (!integration) {
+ throw new HTTPException(404, { message: "GitLab integration not found" });
+ }
+
+ await db
+ .delete(integrationTable)
+ .where(
+ and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitlab"),
+ ),
+ );
+
+ return { success: true, message: "GitLab integration deleted" };
+}
+
+export default deleteGitlabIntegration;
diff --git a/apps/api/src/gitlab-integration/controllers/get-gitlab-integration.ts b/apps/api/src/gitlab-integration/controllers/get-gitlab-integration.ts
new file mode 100644
index 000000000..ab20c82c4
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/get-gitlab-integration.ts
@@ -0,0 +1,56 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../database";
+import { integrationTable } from "../../database/schema";
+import {
+ defaultGitlabConfig,
+ type GitlabConfig,
+} from "../../plugins/gitlab/config";
+import { tokenTypeOf } from "../../plugins/gitlab/utils/gitlab-api";
+import { normalizeApiServerUrl } from "../../utils/openapi-spec";
+
+function maskToken(token: string): string {
+ if (token.length <= 8) {
+ return "••••••••";
+ }
+ return `${token.slice(0, 4)}••••••${token.slice(-4)}`;
+}
+
+async function getGitlabIntegration(
+ projectId: string,
+ includeWebhookSecret = false,
+) {
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "gitlab"),
+ ),
+ });
+
+ if (!integration) {
+ return null;
+ }
+
+ const config = JSON.parse(integration.config) as GitlabConfig;
+
+ const apiBase = normalizeApiServerUrl(
+ process.env.KANEO_API_URL || "http://localhost:1337",
+ );
+
+ return {
+ id: integration.id,
+ projectId: integration.projectId,
+ baseUrl: config.baseUrl,
+ projectPath: config.projectPath,
+ tokenType: tokenTypeOf(config),
+ maskedAccessToken: maskToken(config.accessToken),
+ webhookUrl: `${apiBase.replace(/\/$/, "")}/gitlab-integration/webhook/${integration.id}`,
+ webhookSecret: includeWebhookSecret ? (config.webhookSecret ?? "") : "",
+ branchPattern: config.branchPattern || defaultGitlabConfig.branchPattern,
+ commentTaskLinkOnGitlabIssue: config.commentTaskLinkOnGitlabIssue !== false,
+ isActive: integration.isActive,
+ createdAt: integration.createdAt,
+ updatedAt: integration.updatedAt,
+ };
+}
+
+export default getGitlabIntegration;
diff --git a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts
new file mode 100644
index 000000000..30a90688b
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts
@@ -0,0 +1,416 @@
+import { and, eq, inArray, notInArray } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ activityTable,
+ integrationTable,
+ labelTable,
+ projectTable,
+ taskTable,
+} from "../../database/schema";
+import { publishEvent } from "../../events";
+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 type { GitlabConfig } from "../../plugins/gitlab/config";
+import { extractTaskNumberGitlab } from "../../plugins/gitlab/utils/branch-matcher";
+import {
+ createGitlabClient,
+ type GitlabIssue,
+ type GitlabMergeRequest,
+} from "../../plugins/gitlab/utils/gitlab-api";
+import { isSystemLabelName } from "../../plugins/gitlab/utils/system-labels";
+import { claimTaskNumber } from "../../task/controllers/claim-task-numbers";
+
+type ImportResult = {
+ imported: number;
+ updated: number;
+ skipped: number;
+ errors?: string[];
+};
+
+type GitlabClient = ReturnType<typeof createGitlabClient>;
+
+const PER_PAGE = 100;
+const MAX_PAGES = 50;
+
+export async function importGitlabIssues(
+ 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, "gitlab"),
+ ),
+ });
+
+ if (!integration) {
+ throw new HTTPException(404, { message: "GitLab integration not found" });
+ }
+
+ if (!integration.isActive) {
+ throw new HTTPException(400, {
+ message: "GitLab integration is not active",
+ });
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn("Invalid GitLab integration config JSON", {
+ integrationId: integration.id,
+ error,
+ });
+ throw new HTTPException(400, {
+ message: `Invalid GitLab integration config: ${message}`,
+ });
+ }
+
+ if (!config.accessToken || !config.baseUrl) {
+ throw new HTTPException(400, {
+ message: "GitLab access token or base URL not configured",
+ });
+ }
+
+ const client = createGitlabClient(config);
+
+ const allIssues: GitlabIssue[] = [];
+ for (let page = 1; page <= MAX_PAGES; page++) {
+ const issues = await client.listIssues(config.projectPath, page, "opened");
+ if (issues.length === 0) break;
+ allIssues.push(...issues);
+ if (issues.length < PER_PAGE) break;
+ }
+
+ 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 message = error instanceof Error ? error.message : String(error);
+ errors.push(`Issue !${issue.iid}: ${message}`);
+ }
+ }
+
+ const allMergeRequests: GitlabMergeRequest[] = [];
+ for (let page = 1; page <= MAX_PAGES; page++) {
+ const mergeRequests = await client.listMergeRequests(
+ config.projectPath,
+ page,
+ );
+ if (mergeRequests.length === 0) break;
+ allMergeRequests.push(...mergeRequests);
+ if (mergeRequests.length < PER_PAGE) break;
+ }
+
+ for (const mergeRequest of allMergeRequests) {
+ try {
+ await linkMergeRequestToTask(
+ mergeRequest,
+ integration.id,
+ projectId,
+ project.slug,
+ config,
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ errors.push(`Merge request !${mergeRequest.iid}: ${message}`);
+ }
+ }
+
+ return {
+ imported,
+ updated,
+ skipped,
+ ...(errors.length > 0 ? { errors } : {}),
+ };
+}
+
+async function importSingleIssue(
+ issue: GitlabIssue,
+ integrationId: string,
+ projectId: string,
+ workspaceId: string,
+ config: GitlabConfig,
+ client: GitlabClient,
+): Promise<"imported" | "updated" | "skipped"> {
+ const existingLink = await findExternalLink(
+ integrationId,
+ "issue",
+ issue.iid.toString(),
+ );
+
+ const labels = issue.labels ?? [];
+ const priority = extractIssuePriority(labels);
+ const status = extractIssueStatus(labels);
+
+ if (existingLink) {
+ const updateData: Record<string, unknown> = {
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.description),
+ };
+
+ 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 importNotesForTask(issue, existingLink.taskId, config, client);
+
+ return "updated";
+ }
+
+ // The project's own counter is the allocator every other task creation path
+ // uses, so deriving a number from max(number) here would hand the next
+ // webhook a number that is already taken.
+ const createdTask = await db.transaction(async (tx) => {
+ const number = await claimTaskNumber(projectId, tx);
+
+ const taskValues: typeof taskTable.$inferInsert = {
+ projectId,
+ userId: null,
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.description),
+ status: status || "to-do",
+ priority: priority ?? "low",
+ number,
+ };
+
+ 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,
+ integrationId,
+ resourceType: "issue",
+ externalId: issue.iid.toString(),
+ url: issue.web_url,
+ title: issue.title,
+ metadata: {
+ state: issue.state,
+ createdFrom: "gitlab-import",
+ author: issue.author?.username ?? issue.author?.name,
+ },
+ });
+
+ await importLabelsForTask(labels, createdTask.id, workspaceId);
+ await importNotesForTask(issue, createdTask.id, config, client);
+
+ await publishEvent("task.created", {
+ ...createdTask,
+ taskId: createdTask.id,
+ userId: createdTask.userId ?? "",
+ type: "task",
+ content: null,
+ source: "gitlab-import",
+ integrationId,
+ externalId: issue.iid.toString(),
+ });
+
+ return "imported";
+}
+
+async function importLabelsForTask(
+ issueLabels: string[],
+ taskId: string,
+ workspaceId: string,
+): Promise<void> {
+ const names = issueLabels.filter((name) => name && !isSystemLabelName(name));
+
+ if (names.length > 0) {
+ await db
+ .delete(labelTable)
+ .where(
+ and(eq(labelTable.taskId, taskId), notInArray(labelTable.name, names)),
+ );
+ } else {
+ await db.delete(labelTable).where(eq(labelTable.taskId, taskId));
+ return;
+ }
+
+ const existingLabelsOnTask = await db.query.labelTable.findMany({
+ where: and(eq(labelTable.taskId, taskId), inArray(labelTable.name, names)),
+ });
+
+ for (const name of names) {
+ if (existingLabelsOnTask.some((label) => label.name === name)) {
+ continue;
+ }
+
+ const existingWorkspaceLabel = await db.query.labelTable.findFirst({
+ where: and(
+ eq(labelTable.workspaceId, workspaceId),
+ eq(labelTable.name, name),
+ ),
+ });
+
+ await db
+ .insert(labelTable)
+ .values({
+ name,
+ color: existingWorkspaceLabel?.color || "#6B7280",
+ taskId,
+ workspaceId,
+ })
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
+ }
+}
+
+async function importNotesForTask(
+ issue: GitlabIssue,
+ taskId: string,
+ config: GitlabConfig,
+ client: GitlabClient,
+): Promise<void> {
+ for (let page = 1; page <= MAX_PAGES; page++) {
+ const notes = await client.listIssueNotes(
+ config.projectPath,
+ issue.iid,
+ page,
+ PER_PAGE,
+ );
+
+ if (notes.length === 0) break;
+
+ for (const note of notes) {
+ // GitLab records label, milestone and state changes as system notes.
+ if (note.system) {
+ continue;
+ }
+
+ const username = note.author?.username ?? note.author?.name ?? "";
+
+ await db
+ .insert(activityTable)
+ .values({
+ taskId,
+ type: "comment",
+ content: note.body,
+ externalUserName: username || "Unknown",
+ externalUserAvatar: note.author?.avatar_url ?? null,
+ externalSource: "gitlab",
+ // The notes API returns no URL for a note, and the anchor on the
+ // issue page is how GitLab itself links to one.
+ externalUrl: `${issue.web_url}#note_${note.id}`,
+ eventData: {
+ externalCommentId: note.id,
+ },
+ })
+ .onConflictDoNothing({
+ target: [
+ activityTable.taskId,
+ activityTable.externalSource,
+ activityTable.externalUrl,
+ ],
+ });
+ }
+
+ if (notes.length < PER_PAGE) break;
+ }
+}
+
+async function linkMergeRequestToTask(
+ mergeRequest: GitlabMergeRequest,
+ integrationId: string,
+ projectId: string,
+ projectSlug: string,
+ config: GitlabConfig,
+): Promise<void> {
+ const branchName = mergeRequest.source_branch;
+
+ if (!branchName) {
+ return;
+ }
+
+ const taskNumber = extractTaskNumberGitlab(
+ branchName,
+ mergeRequest.title,
+ mergeRequest.description ?? undefined,
+ config,
+ projectSlug,
+ );
+
+ if (!taskNumber) {
+ return;
+ }
+
+ const task = await findTaskByNumber(projectId, taskNumber);
+
+ if (!task) {
+ return;
+ }
+
+ const existingLink = await findExternalLink(
+ integrationId,
+ "pull_request",
+ mergeRequest.iid.toString(),
+ );
+
+ if (existingLink) {
+ return;
+ }
+
+ await createExternalLink({
+ taskId: task.id,
+ integrationId,
+ resourceType: "pull_request",
+ externalId: mergeRequest.iid.toString(),
+ url: mergeRequest.web_url,
+ title: mergeRequest.title,
+ metadata: {
+ state: mergeRequest.state,
+ draft: mergeRequest.draft === true,
+ merged: false,
+ branch: branchName,
+ author: mergeRequest.author?.username ?? mergeRequest.author?.name,
+ },
+ });
+}
diff --git a/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts b/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts
new file mode 100644
index 000000000..8172bee6e
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts
@@ -0,0 +1,69 @@
+import { HTTPException } from "hono/http-exception";
+import type { GitlabTokenType } from "../../plugins/gitlab/config";
+import { normalizeGitlabBaseUrl } from "../../plugins/gitlab/config";
+import {
+ createGitlabClient,
+ verifyGitlabToken,
+} from "../../plugins/gitlab/utils/gitlab-api";
+
+type ProjectRow = {
+ id: number;
+ name: string;
+ path_with_namespace: string;
+ name_with_namespace: string;
+ visibility: string;
+ web_url: string;
+};
+
+const PER_PAGE = 50;
+const MAX_PAGES = 50;
+
+async function listGitlabProjects({
+ baseUrl,
+ accessToken,
+ tokenType,
+}: {
+ baseUrl: string;
+ accessToken: string;
+ tokenType: GitlabTokenType;
+}): Promise<{ projects: ProjectRow[] }> {
+ const normalized = normalizeGitlabBaseUrl(baseUrl);
+
+ try {
+ await verifyGitlabToken(normalized, accessToken, tokenType);
+ } catch {
+ throw new HTTPException(401, {
+ message: "Invalid GitLab token or could not reach instance.",
+ });
+ }
+
+ const client = createGitlabClient({
+ baseUrl: normalized,
+ accessToken,
+ tokenType,
+ });
+
+ const projects: ProjectRow[] = [];
+
+ for (let page = 1; page <= MAX_PAGES; page++) {
+ const batch = await client.listMemberProjects(page, PER_PAGE);
+ if (batch.length === 0) break;
+
+ for (const project of batch) {
+ projects.push({
+ id: project.id,
+ name: project.name,
+ path_with_namespace: project.path_with_namespace,
+ name_with_namespace: project.name_with_namespace,
+ visibility: project.visibility,
+ web_url: project.web_url,
+ });
+ }
+
+ if (batch.length < PER_PAGE) break;
+ }
+
+ return { projects };
+}
+
+export default listGitlabProjects;
diff --git a/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts b/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts
new file mode 100644
index 000000000..26e521283
--- /dev/null
+++ b/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts
@@ -0,0 +1,131 @@
+import { HTTPException } from "hono/http-exception";
+import type { GitlabTokenType } from "../../plugins/gitlab/config";
+import { normalizeGitlabBaseUrl } from "../../plugins/gitlab/config";
+import {
+ createGitlabClient,
+ GitlabApiError,
+ type GitlabProject,
+ verifyGitlabToken,
+} from "../../plugins/gitlab/utils/gitlab-api";
+
+// Managing issue labels needs Developer. Reporter can open an issue but cannot
+// create the priority and status labels Kaneo relies on.
+const REQUIRED_ACCESS_LEVEL = 30;
+
+function highestAccessLevel(project: GitlabProject): number {
+ const permissions = project.permissions;
+ return Math.max(
+ permissions?.project_access?.access_level ?? 0,
+ permissions?.group_access?.access_level ?? 0,
+ );
+}
+
+function failure(
+ message: string,
+ failureReason: "not_a_gitlab_instance" | "redirected" | "project_not_found",
+) {
+ return {
+ isInstalled: false,
+ hasRequiredPermissions: false,
+ projectExists: false,
+ projectVisibility: null,
+ missingPermissions: [] as string[],
+ message,
+ failureReason,
+ };
+}
+
+async function verifyGitlabAccess({
+ baseUrl,
+ accessToken,
+ tokenType,
+ projectPath,
+}: {
+ baseUrl: string;
+ accessToken: string;
+ tokenType: GitlabTokenType;
+ projectPath: string;
+}) {
+ try {
+ const normalized = normalizeGitlabBaseUrl(baseUrl);
+
+ try {
+ await verifyGitlabToken(normalized, accessToken, tokenType);
+ } catch (error) {
+ // A 404 from /user means the URL does not serve the GitLab API, not that
+ // a project is missing.
+ if (error instanceof GitlabApiError && error.status === 404) {
+ return failure(
+ "The URL does not point to a GitLab instance.",
+ "not_a_gitlab_instance",
+ );
+ }
+ throw error;
+ }
+
+ const client = createGitlabClient({
+ baseUrl: normalized,
+ accessToken,
+ tokenType,
+ });
+
+ const project = await client.getProject(projectPath);
+
+ // A group or instance token carries no per-project access level, so a
+ // missing level is not proof of missing rights -- the project answering at
+ // all already means the token can read it.
+ const accessLevel = highestAccessLevel(project);
+ const hasRequiredPermissions =
+ accessLevel === 0 || accessLevel >= REQUIRED_ACCESS_LEVEL;
+
+ return {
+ isInstalled: true,
+ hasRequiredPermissions,
+ projectExists: true,
+ projectVisibility: project.visibility,
+ missingPermissions: hasRequiredPermissions ? [] : ["Developer"],
+ message: hasRequiredPermissions
+ ? "Token can access the project."
+ : "Token may not have sufficient permissions to manage issues and labels.",
+ failureReason: null,
+ };
+ } catch (error) {
+ if (error instanceof GitlabApiError) {
+ if (error.kind === "REDIRECT") {
+ return failure(
+ `The GitLab URL redirected (HTTP ${error.status}). This usually means the server forces HTTPS. Please use the final URL directly.`,
+ "redirected",
+ );
+ }
+
+ if (error.kind === "INVALID_JSON") {
+ return failure(
+ "The URL does not point to a GitLab instance.",
+ "not_a_gitlab_instance",
+ );
+ }
+
+ if (error.status === 404) {
+ return failure(
+ "Project not found or not accessible with this token.",
+ "project_not_found",
+ );
+ }
+
+ if (error.status === 401 || error.status === 403) {
+ throw new HTTPException(401, {
+ message: "Invalid GitLab token or unauthorized.",
+ });
+ }
+ }
+
+ throw new HTTPException(500, {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Failed to verify GitLab access",
+ });
+ }
+}
+
+export default verifyGitlabAccess;
diff --git a/apps/api/src/gitlab-integration/index.ts b/apps/api/src/gitlab-integration/index.ts
new file mode 100644
index 000000000..356e653b2
--- /dev/null
+++ b/apps/api/src/gitlab-integration/index.ts
@@ -0,0 +1,366 @@
+import { and, eq } from "drizzle-orm";
+import type { Context } from "hono";
+import { HTTPException } from "hono/http-exception";
+import db from "../database";
+import { integrationTable } from "../database/schema";
+import { scopeToProjectFromBody } from "../integrations/middleware";
+import { projectIdBody, projectIdParam } from "../integrations/schema";
+import {
+ apiRouter,
+ type BaseVariables,
+ createRoute,
+ errorResponse,
+ jsonResponse,
+} from "../openapi";
+import {
+ type GitlabConfig,
+ validateGitlabConfig,
+} from "../plugins/gitlab/config";
+import { tokenTypeOf } from "../plugins/gitlab/utils/gitlab-api";
+import { handleGitlabWebhookRequest } from "../plugins/gitlab/webhook-handler";
+import {
+ hasWorkspacePermission,
+ requireWorkspacePermission,
+} from "../utils/require-workspace-permission";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+import createGitlabIntegration from "./controllers/create-gitlab-integration";
+import deleteGitlabIntegration from "./controllers/delete-gitlab-integration";
+import getGitlabIntegration from "./controllers/get-gitlab-integration";
+import { importGitlabIssues } from "./controllers/import-gitlab-issues";
+import listGitlabProjects from "./controllers/list-gitlab-projects";
+import verifyGitlabAccess from "./controllers/verify-gitlab-access";
+import {
+ gitlabDeleteResultSchema,
+ gitlabImportResultSchema,
+ gitlabIntegrationSchema,
+ gitlabProjectListSchema,
+ gitlabVerificationResultSchema,
+ integrationNotFoundSchema,
+} from "./response";
+import {
+ createGitlabBody,
+ listGitlabProjectsBody,
+ updateGitlabBody,
+ verifyGitlabBody,
+} from "./schema";
+
+const manageAccess = [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ workspace: ["manage_settings"] }),
+];
+
+const listProjectsRoute = createRoute({
+ method: "post",
+ operationId: "listGitlabProjects",
+ path: "/projects",
+ tags: ["GitLab"],
+ summary: "List GitLab projects",
+ description:
+ "List the projects a GitLab token is a member of, for picking one to link. Sent as a POST because the token travels in the body rather than the URL.",
+ middleware: manageAccess,
+ request: {
+ body: {
+ required: true,
+ content: { "application/json": { schema: listGitlabProjectsBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Accessible projects", gitlabProjectListSchema),
+ 400: errorResponse("Invalid body, or unknown project"),
+ 401: errorResponse(
+ "GitLab rejected the token, or the instance is unreachable",
+ ),
+ 403: errorResponse(
+ "No workspace access, or missing workspace:manage_settings",
+ ),
+ },
+});
+
+const verifyRoute = createRoute({
+ method: "post",
+ operationId: "verifyGitlabAccess",
+ path: "/verify",
+ tags: ["GitLab"],
+ summary: "Verify GitLab access",
+ description:
+ "Check that the base URL is a GitLab instance and that the token can reach the project with the permissions Kaneo needs. An unreachable instance, a missing project, or insufficient permissions are reported in a 200 body so the form can explain them; a token GitLab rejects outright is a 401.",
+ middleware: manageAccess,
+ request: {
+ body: {
+ required: true,
+ content: { "application/json": { schema: verifyGitlabBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Verification result", gitlabVerificationResultSchema),
+ 400: errorResponse("Invalid body, or unknown project"),
+ 401: errorResponse("GitLab rejected the token"),
+ 403: errorResponse(
+ "No workspace access, or missing workspace:manage_settings",
+ ),
+ },
+});
+
+const getIntegrationRoute = createRoute({
+ method: "get",
+ operationId: "getGitlabIntegration",
+ path: "/project/{projectId}",
+ tags: ["GitLab"],
+ summary: "Get GitLab integration",
+ description:
+ "Get the GitLab integration for a project, or null when none is configured. The webhook secret is included only for callers with workspace:manage_settings.",
+ middleware: [workspaceAccess.fromProject("projectId")] as const,
+ request: { params: projectIdParam },
+ responses: {
+ 200: jsonResponse(
+ "GitLab integration details, or null",
+ gitlabIntegrationSchema.nullable(),
+ ),
+ 400: errorResponse(
+ "Unknown project, or its workspace could not be determined",
+ ),
+ 403: errorResponse("No access to the project's workspace"),
+ },
+});
+
+const createIntegrationRoute = createRoute({
+ method: "post",
+ operationId: "createGitlabIntegration",
+ path: "/project/{projectId}",
+ tags: ["GitLab"],
+ summary: "Create GitLab integration",
+ description:
+ "Link a project to a GitLab project. Kaneo generates the secret GitLab must send with each webhook; add the webhook in GitLab afterwards. Use the verify route first to confirm the token really reaches the project.",
+ middleware: manageAccess,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: createGitlabBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("The stored integration", gitlabIntegrationSchema),
+ 400: errorResponse("Invalid body, or unknown project"),
+ 403: errorResponse(
+ "No workspace access, or missing workspace:manage_settings",
+ ),
+ 409: errorResponse(
+ "That GitLab project is already linked to another Kaneo project",
+ ),
+ },
+});
+
+const updateIntegrationRoute = createRoute({
+ method: "patch",
+ operationId: "updateGitlabIntegration",
+ path: "/project/{projectId}",
+ tags: ["GitLab"],
+ summary: "Update GitLab integration",
+ description:
+ "Update the GitLab integration. Omitted fields keep their current value.",
+ middleware: manageAccess,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: updateGitlabBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("The updated integration", gitlabIntegrationSchema),
+ 400: errorResponse("The resulting config failed validation"),
+ 403: errorResponse(
+ "No workspace access, or missing workspace:manage_settings",
+ ),
+ 404: jsonResponse("Integration not found", integrationNotFoundSchema),
+ },
+});
+
+const deleteIntegrationRoute = createRoute({
+ method: "delete",
+ operationId: "deleteGitlabIntegration",
+ path: "/project/{projectId}",
+ tags: ["GitLab"],
+ summary: "Delete GitLab integration",
+ description: "Unlink a project from its GitLab project.",
+ middleware: manageAccess,
+ request: { params: projectIdParam },
+ responses: {
+ 200: jsonResponse("The integration was removed", gitlabDeleteResultSchema),
+ 400: errorResponse(
+ "Unknown project, or its workspace could not be determined",
+ ),
+ 403: errorResponse(
+ "No workspace access, or missing workspace:manage_settings",
+ ),
+ 404: errorResponse("GitLab integration not found"),
+ },
+});
+
+const importIssuesRoute = createRoute({
+ method: "post",
+ operationId: "importGitlabIssues",
+ path: "/import-issues",
+ tags: ["GitLab"],
+ summary: "Import GitLab issues",
+ description:
+ "Import the linked project's open issues as tasks. Issues that already have a task are refreshed rather than duplicated.",
+ middleware: [
+ scopeToProjectFromBody,
+ requireWorkspacePermission({ task: ["create"] }),
+ ] as const,
+ request: {
+ body: {
+ required: true,
+ content: { "application/json": { schema: projectIdBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Import summary", gitlabImportResultSchema),
+ 400: errorResponse("projectId is required"),
+ 403: errorResponse(
+ "No workspace access, or missing task:create permission",
+ ),
+ 404: errorResponse("Project not found"),
+ },
+});
+
+const gitlabIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
+ .openapi(listProjectsRoute, async (c) => {
+ const { baseUrl, accessToken, tokenType } = c.req.valid("json");
+ const result = await listGitlabProjects({
+ baseUrl,
+ accessToken,
+ tokenType: tokenTypeOf({ tokenType }),
+ });
+ return c.json(result, 200);
+ })
+ .openapi(verifyRoute, async (c) => {
+ const body = c.req.valid("json");
+ const result = await verifyGitlabAccess({
+ ...body,
+ tokenType: tokenTypeOf(body),
+ });
+ return c.json(result, 200);
+ })
+ .openapi(getIntegrationRoute, async (c) => {
+ const { projectId } = c.req.valid("param");
+ const includeWebhookSecret = await hasWorkspacePermission(c, {
+ workspace: ["manage_settings"],
+ });
+ const integration = await getGitlabIntegration(
+ projectId,
+ includeWebhookSecret,
+ );
+ if (!integration) {
+ return c.json(null, 200);
+ }
+ return c.json(integration, 200);
+ })
+ .openapi(createIntegrationRoute, async (c) => {
+ const { projectId } = c.req.valid("param");
+ const body = c.req.valid("json");
+ await createGitlabIntegration({
+ projectId,
+ baseUrl: body.baseUrl,
+ accessToken: body.accessToken,
+ tokenType: tokenTypeOf(body),
+ projectPath: body.projectPath,
+ });
+ const integration = await getGitlabIntegration(projectId, true);
+ if (!integration) {
+ throw new HTTPException(500, { message: "Failed to load integration" });
+ }
+ return c.json(integration, 200);
+ })
+ .openapi(updateIntegrationRoute, 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, "gitlab"),
+ ),
+ });
+
+ if (!row) {
+ return c.json({ error: "Integration not found" }, 404);
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(row.config) as GitlabConfig;
+ } catch {
+ throw new HTTPException(500, { message: "Invalid integration config" });
+ }
+
+ if (body.commentTaskLinkOnGitlabIssue !== undefined) {
+ config = {
+ ...config,
+ commentTaskLinkOnGitlabIssue: body.commentTaskLinkOnGitlabIssue,
+ };
+ }
+
+ const validation = await validateGitlabConfig(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, "gitlab"),
+ ),
+ );
+
+ const updated = await getGitlabIntegration(projectId, true);
+ if (!updated) {
+ throw new HTTPException(500, { message: "Failed to load integration" });
+ }
+ return c.json(updated, 200);
+ })
+ .openapi(deleteIntegrationRoute, async (c) => {
+ const { projectId } = c.req.valid("param");
+ const result = await deleteGitlabIntegration(projectId);
+ return c.json(result, 200);
+ })
+ .openapi(importIssuesRoute, async (c) => {
+ const { projectId } = c.req.valid("json");
+ const result = await importGitlabIssues(projectId);
+ return c.json(result, 200);
+ });
+
+export async function handleGitlabWebhookRoute(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 token =
+ c.req.header("x-gitlab-token") || c.req.header("X-Gitlab-Token");
+
+ const result = await handleGitlabWebhookRequest(integrationId, body, token);
+
+ if (!result.success) {
+ return c.json({ error: result.error }, 400);
+ }
+
+ return c.json({ status: "success" });
+}
+
+export default gitlabIntegration;
diff --git a/apps/api/src/gitlab-integration/response.ts b/apps/api/src/gitlab-integration/response.ts
new file mode 100644
index 000000000..05c4579e5
--- /dev/null
+++ b/apps/api/src/gitlab-integration/response.ts
@@ -0,0 +1,89 @@
+import { responseTimestamp, z } from "../openapi";
+
+// Credentials are only ever returned masked; the webhook secret goes only to
+// callers holding workspace:manage_settings.
+export const gitlabIntegrationSchema = z
+ .object({
+ id: z.string(),
+ projectId: z.string(),
+ baseUrl: z
+ .string()
+ .openapi({ description: "Root URL of the GitLab instance." }),
+ projectPath: z.string().openapi({
+ description: "Full path of the linked project, nested groups included.",
+ }),
+ tokenType: z.enum(["private", "bearer"]),
+ maskedAccessToken: z.string(),
+ webhookUrl: z.string().optional().openapi({
+ description: "Where GitLab should POST events for this project.",
+ }),
+ webhookSecret: z.string().optional().openapi({
+ description:
+ "Only returned to callers with workspace:manage_settings, so the value can be pasted into GitLab.",
+ }),
+ branchPattern: z.string().optional(),
+ commentTaskLinkOnGitlabIssue: z.boolean().optional().openapi({
+ description:
+ "When on, Kaneo comments a link back to the task on the linked GitLab issue.",
+ }),
+ isActive: z.boolean().nullable(),
+ createdAt: responseTimestamp,
+ updatedAt: responseTimestamp,
+ })
+ .openapi("GitlabIntegration");
+
+export const gitlabProjectSchema = z
+ .object({
+ id: z.number(),
+ name: z.string(),
+ path_with_namespace: z.string(),
+ name_with_namespace: z.string(),
+ visibility: z.string(),
+ web_url: z.string(),
+ })
+ .openapi("GitlabProject");
+
+export const gitlabProjectListSchema = z
+ .object({ projects: z.array(gitlabProjectSchema) })
+ .openapi("GitlabProjectList");
+
+export const gitlabVerificationResultSchema = z
+ .object({
+ isInstalled: z.boolean().openapi({
+ description: "The base URL answered as a GitLab instance for this token.",
+ }),
+ hasRequiredPermissions: z.boolean(),
+ projectExists: z.boolean(),
+ projectVisibility: z.string().nullable(),
+ missingPermissions: z.array(z.string()),
+ message: z.string().openapi({
+ description: "A human-readable summary to show the user.",
+ }),
+ failureReason: z
+ .enum(["not_a_gitlab_instance", "redirected", "project_not_found"])
+ .nullable()
+ .openapi({
+ description:
+ "Why verification failed, when it did. `redirected` usually means the base URL is behind a proxy that rewrites it.",
+ }),
+ })
+ .openapi("GitlabVerificationResult");
+
+export const gitlabImportResultSchema = z
+ .object({
+ imported: z.number(),
+ updated: z.number().openapi({
+ description: "Existing tasks that were refreshed from their issue.",
+ }),
+ skipped: z.number(),
+ errors: z.array(z.string()).optional(),
+ })
+ .openapi("GitlabImportResult");
+
+export const gitlabDeleteResultSchema = z
+ .object({ success: z.boolean(), message: z.string() })
+ .openapi("GitlabDeleteResult");
+
+export const integrationNotFoundSchema = z
+ .object({ error: z.string() })
+ .openapi("GitlabIntegrationNotFound");
diff --git a/apps/api/src/gitlab-integration/schema.ts b/apps/api/src/gitlab-integration/schema.ts
new file mode 100644
index 000000000..abdbd4007
--- /dev/null
+++ b/apps/api/src/gitlab-integration/schema.ts
@@ -0,0 +1,37 @@
+import { z } from "../openapi";
+
+const tokenType = z.enum(["private", "bearer"]).optional().openapi({
+ description:
+ "`private` sends the token in PRIVATE-TOKEN, which is what personal, project and group access tokens expect. `bearer` sends it in Authorization, for an OAuth2 token you already hold. Defaults to `private`.",
+});
+
+const gitlabCredentials = {
+ projectId: z.string().min(1),
+ baseUrl: z.url(),
+ accessToken: z.string().min(1),
+ tokenType,
+};
+
+export const listGitlabProjectsBody = z.object(gitlabCredentials);
+
+export const verifyGitlabBody = z.object({
+ ...gitlabCredentials,
+ projectPath: z.string().min(1).openapi({
+ description:
+ "Full path of the GitLab project, including any nested groups, for example acme/platform/web.",
+ }),
+});
+
+export const createGitlabBody = z.object({
+ baseUrl: z.string().min(1),
+ accessToken: z.string().optional().openapi({
+ description: "Omit to keep the token already stored for this project.",
+ }),
+ tokenType,
+ projectPath: z.string().min(1),
+});
+
+export const updateGitlabBody = z.object({
+ isActive: z.boolean().optional(),
+ commentTaskLinkOnGitlabIssue: z.boolean().optional(),
+});
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index a057d8672..a6fdeed6d 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -32,6 +32,9 @@ import giteaIntegration, { handleGiteaWebhookRoute } from "./gitea-integration";
import githubIntegration, {
handleGithubWebhookRoute,
} from "./github-integration";
+import gitlabIntegration, {
+ handleGitlabWebhookRoute,
+} from "./gitlab-integration";
import getInstanceStatus from "./instance/controllers/get-instance-status";
import invitation from "./invitation";
import label from "./label";
@@ -239,6 +242,11 @@ export function createApp() {
handleGiteaWebhookRoute,
);
+ api.post(
+ "/gitlab-integration/webhook/:integrationId",
+ handleGitlabWebhookRoute,
+ );
+
const invitationPublicApi = api.get("/invitation/public/:id", async (c) => {
const { id } = c.req.param();
const result = await getInvitationDetails(id);
@@ -592,6 +600,10 @@ export function createApp() {
githubIntegration,
);
const giteaIntegrationApi = api.route("/gitea-integration", giteaIntegration);
+ const gitlabIntegrationApi = api.route(
+ "/gitlab-integration",
+ gitlabIntegration,
+ );
const genericWebhookIntegrationApi = api.route(
"/generic-webhook-integration",
genericWebhookIntegration,
@@ -765,6 +777,7 @@ export function createApp() {
genericWebhookIntegrationApi,
githubIntegrationApi,
giteaIntegrationApi,
+ gitlabIntegrationApi,
invitationApi,
invitationPublicApi,
labelApi,
@@ -885,6 +898,7 @@ const {
genericWebhookIntegrationApi,
githubIntegrationApi,
giteaIntegrationApi,
+ gitlabIntegrationApi,
invitationApi,
invitationPublicApi,
labelApi,
@@ -931,6 +945,7 @@ export type AppType =
| typeof searchApi
| typeof githubIntegrationApi
| typeof giteaIntegrationApi
+ | typeof gitlabIntegrationApi
| typeof genericWebhookIntegrationApi
| typeof discordIntegrationApi
| typeof mattermostIntegrationApi
diff --git a/apps/api/src/plugins/index.ts b/apps/api/src/plugins/index.ts
index 6d77fd813..f05e8695e 100644
--- a/apps/api/src/plugins/index.ts
+++ b/apps/api/src/plugins/index.ts
@@ -2,6 +2,7 @@ import { discordPlugin } from "./discord";
import { genericWebhookPlugin } from "./generic-webhook";
import { giteaPlugin } from "./gitea";
import { githubPlugin, initializeGitHubPlugin } from "./github";
+import { gitlabPlugin } from "./gitlab";
import { mattermostPlugin } from "./mattermost";
import { initializeEventSubscriptions, registerPlugin } from "./registry";
import { slackPlugin } from "./slack";
@@ -12,6 +13,7 @@ export function initializePlugins() {
registerPlugin(githubPlugin);
registerPlugin(giteaPlugin);
+ registerPlugin(gitlabPlugin);
registerPlugin(slackPlugin);
registerPlugin(mattermostPlugin);
registerPlugin(discordPlugin);
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index f4f27f221..f7b90fb4c 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -2369,6 +2369,228 @@
"skipped"
]
},
+ "GitlabProjectList": {
+ "type": "object",
+ "properties": {
+ "projects": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GitlabProject"
+ }
+ }
+ },
+ "required": [
+ "projects"
+ ]
+ },
+ "GitlabProject": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "number"
+ },
+ "name": {
+ "type": "string"
+ },
+ "path_with_namespace": {
+ "type": "string"
+ },
+ "name_with_namespace": {
+ "type": "string"
+ },
+ "visibility": {
+ "type": "string"
+ },
+ "web_url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "path_with_namespace",
+ "name_with_namespace",
+ "visibility",
+ "web_url"
+ ]
+ },
+ "GitlabVerificationResult": {
+ "type": "object",
+ "properties": {
+ "isInstalled": {
+ "type": "boolean",
+ "description": "The base URL answered as a GitLab instance for this token."
+ },
+ "hasRequiredPermissions": {
+ "type": "boolean"
+ },
+ "projectExists": {
+ "type": "boolean"
+ },
+ "projectVisibility": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "missingPermissions": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "message": {
+ "type": "string",
+ "description": "A human-readable summary to show the user."
+ },
+ "failureReason": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "enum": [
+ "not_a_gitlab_instance",
+ "redirected",
+ "project_not_found",
+ null
+ ],
+ "description": "Why verification failed, when it did. `redirected` usually means the base URL is behind a proxy that rewrites it."
+ }
+ },
+ "required": [
+ "isInstalled",
+ "hasRequiredPermissions",
+ "projectExists",
+ "projectVisibility",
+ "missingPermissions",
+ "message",
+ "failureReason"
+ ]
+ },
+ "GitlabIntegration": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "projectId": {
+ "type": "string"
+ },
+ "baseUrl": {
+ "type": "string",
+ "description": "Root URL of the GitLab instance."
+ },
+ "projectPath": {
+ "type": "string",
+ "description": "Full path of the linked project, nested groups included."
+ },
+ "tokenType": {
+ "type": "string",
+ "enum": [
+ "private",
+ "bearer"
+ ]
+ },
+ "maskedAccessToken": {
+ "type": "string"
+ },
+ "webhookUrl": {
+ "type": "string",
+ "description": "Where GitLab should POST events for this project."
+ },
+ "webhookSecret": {
+ "type": "string",
+ "description": "Only returned to callers with workspace:manage_settings, so the value can be pasted into GitLab."
+ },
+ "branchPattern": {
+ "type": "string"
+ },
+ "commentTaskLinkOnGitlabIssue": {
+ "type": "boolean",
+ "description": "When on, Kaneo comments a link back to the task on the linked GitLab issue."
+ },
+ "isActive": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time"
+ }
+ },
+ "required": [
+ "id",
+ "projectId",
+ "baseUrl",
+ "projectPath",
+ "tokenType",
+ "maskedAccessToken",
+ "isActive",
+ "createdAt",
+ "updatedAt"
+ ]
+ },
+ "GitlabIntegrationNotFound": {
+ "type": "object",
+ "properties": {
+ "error": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "error"
+ ]
+ },
+ "GitlabDeleteResult": {
+ "type": "object",
+ "properties": {
+ "success": {
+ "type": "boolean"
+ },
+ "message": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "success",
+ "message"
+ ]
+ },
+ "GitlabImportResult": {
+ "type": "object",
+ "properties": {
+ "imported": {
+ "type": "number"
+ },
+ "updated": {
+ "type": "number",
+ "description": "Existing tasks that were refreshed from their issue."
+ },
+ "skipped": {
+ "type": "number"
+ },
+ "errors": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "imported",
+ "updated",
+ "skipped"
+ ]
+ },
"GenericWebhookIntegration": {
"type": [
"object",
@@ -11254,6 +11476,561 @@
}
}
},
+ "/gitlab-integration/projects": {
+ "post": {
+ "operationId": "listGitlabProjects",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "List GitLab projects",
+ "description": "List the projects a GitLab token is a member of, for picking one to link. Sent as a POST because the token travels in the body rather than the URL.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "projectId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "baseUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "accessToken": {
+ "type": "string",
+ "minLength": 1
+ },
+ "tokenType": {
+ "type": "string",
+ "enum": [
+ "private",
+ "bearer"
+ ],
+ "description": "`private` sends the token in PRIVATE-TOKEN, which is what personal, project and group access tokens expect. `bearer` sends it in Authorization, for an OAuth2 token you already hold. Defaults to `private`."
+ }
+ },
+ "required": [
+ "projectId",
+ "baseUrl",
+ "accessToken"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Accessible projects",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabProjectList"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid body, or unknown project",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "GitLab rejected the token, or the instance is unreachable",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "No workspace access, or missing workspace:manage_settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gitlab-integration/verify": {
+ "post": {
+ "operationId": "verifyGitlabAccess",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Verify GitLab access",
+ "description": "Check that the base URL is a GitLab instance and that the token can reach the project with the permissions Kaneo needs. An unreachable instance, a missing project, or insufficient permissions are reported in a 200 body so the form can explain them; a token GitLab rejects outright is a 401.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "projectId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "baseUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "accessToken": {
+ "type": "string",
+ "minLength": 1
+ },
+ "tokenType": {
+ "type": "string",
+ "enum": [
+ "private",
+ "bearer"
+ ],
+ "description": "`private` sends the token in PRIVATE-TOKEN, which is what personal, project and group access tokens expect. `bearer` sends it in Authorization, for an OAuth2 token you already hold. Defaults to `private`."
+ },
+ "projectPath": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Full path of the GitLab project, including any nested groups, for example acme/platform/web."
+ }
+ },
+ "required": [
+ "projectId",
+ "baseUrl",
+ "accessToken",
+ "projectPath"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Verification result",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabVerificationResult"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid body, or unknown project",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "GitLab rejected the token",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "No workspace access, or missing workspace:manage_settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gitlab-integration/project/{projectId}": {
+ "get": {
+ "operationId": "getGitlabIntegration",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Get GitLab integration",
+ "description": "Get the GitLab integration for a project, or null when none is configured. The webhook secret is included only for callers with workspace:manage_settings.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "GitLab integration details, or null",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabIntegration"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Unknown project, or its workspace could not be determined",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "No access to the project's workspace",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "operationId": "createGitlabIntegration",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Create GitLab integration",
+ "description": "Link a project to a GitLab project. Kaneo generates the secret GitLab must send with each webhook; add the webhook in GitLab afterwards. Use the verify route first to confirm the token really reaches the project.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "baseUrl": {
+ "type": "string",
+ "minLength": 1
+ },
+ "accessToken": {
+ "type": "string",
+ "description": "Omit to keep the token already stored for this project."
+ },
+ "tokenType": {
+ "type": "string",
+ "enum": [
+ "private",
+ "bearer"
+ ],
+ "description": "`private` sends the token in PRIVATE-TOKEN, which is what personal, project and group access tokens expect. `bearer` sends it in Authorization, for an OAuth2 token you already hold. Defaults to `private`."
+ },
+ "projectPath": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "baseUrl",
+ "projectPath"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The stored integration",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabIntegration"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid body, or unknown project",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "No workspace access, or missing workspace:manage_settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "That GitLab project is already linked to another Kaneo project",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "patch": {
+ "operationId": "updateGitlabIntegration",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Update GitLab integration",
+ "description": "Update the GitLab integration. Omitted fields keep their current value.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "isActive": {
+ "type": "boolean"
+ },
+ "commentTaskLinkOnGitlabIssue": {
+ "type": "boolean"
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The updated integration",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabIntegration"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The resulting config failed validation",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "No workspace access, or missing workspace:manage_settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Integration not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabIntegrationNotFound"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "operationId": "deleteGitlabIntegration",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Delete GitLab integration",
+ "description": "Unlink a project from its GitLab project.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The integration was removed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabDeleteResult"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Unknown project, or its workspace could not be determined",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "No workspace access, or missing workspace:manage_settings",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "GitLab integration not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/gitlab-integration/import-issues": {
+ "post": {
+ "operationId": "importGitlabIssues",
+ "tags": [
+ "GitLab"
+ ],
+ "summary": "Import GitLab issues",
+ "description": "Import the linked project's open issues as tasks. Issues that already have a task are refreshed rather than duplicated.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "projectId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "projectId"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Import summary",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GitlabImportResult"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "projectId is required",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "No workspace access, or missing task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/generic-webhook-integration/project/{projectId}": {
"get": {
"operationId": "getGenericWebhookIntegration",