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.

12.4 KB
Raw Blame
import { and, eq } from "drizzle-orm";
import type { Context } from "hono";
import { HTTPException } from "hono/http-exception";
import db from "../database";
import { publishEvent } from "../events";
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,
} 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"),
    401: errorResponse(
      "GitLab rejected the token, or the instance is unreachable",
    ),
    403: errorResponse(
      "No access to the project, or missing workspace:manage_settings",
    ),
    404: errorResponse("Project not found"),
  },
});

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"),
    401: errorResponse("GitLab rejected the token"),
    403: errorResponse(
      "No access to the project, or missing workspace:manage_settings",
    ),
    404: errorResponse("Project not found"),
  },
});

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 masked access token and the webhook secret are included only for callers with workspace:manage_settings.",
  middleware: [
    workspaceAccess.fromProject("projectId"),
    requireWorkspacePermission({ project: ["read"] }),
  ] as const,
  request: { params: projectIdParam },
  responses: {
    200: jsonResponse(
      "GitLab integration details, or null",
      gitlabIntegrationSchema.nullable(),
    ),
    403: errorResponse(
      "No access to the project, or missing project:read permission",
    ),
    404: errorResponse("Project not found"),
  },
});

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"),
    403: errorResponse(
      "No access to the project, or missing workspace:manage_settings",
    ),
    409: errorResponse(
      "That GitLab project is already linked to another Kaneo project",
    ),
    404: errorResponse("Project not found"),
  },
});

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 access to the project, or missing workspace:manage_settings",
    ),
    404: errorResponse("Project or integration not found"),
    409: errorResponse("Integration changed; refresh before updating settings"),
  },
});

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),
    403: errorResponse(
      "No access to the project, or missing workspace:manage_settings",
    ),
    404: errorResponse("Project or 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. Requires task:create and task:update permissions.",
  middleware: [
    scopeToProjectFromBody,
    requireWorkspacePermission({ task: ["create", "update"] }),
  ] 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 access to the project, or missing task:create or task:update 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 includeSecrets = await hasWorkspacePermission(c, {
      workspace: ["manage_settings"],
    });
    const integration = await getGitlabIntegration(projectId, includeSecrets);
    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" });
    }
    if (integration)
      await publishEvent("integration.sync_rules_changed", {
        projectId,
        integrationId: integration.id,
      });
    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) {
      throw new HTTPException(404, { message: "Integration not found" });
    }

    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",
      });
    }

    const [saved] = 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.id, row.id),
          eq(integrationTable.config, row.config),
        ),
      )
      .returning({ id: integrationTable.id });
    if (!saved)
      throw new HTTPException(409, {
        message: "Integration changed; refresh before updating settings",
      });

    const updated = await getGitlabIntegration(projectId, true);
    if (!updated) {
      throw new HTTPException(500, { message: "Failed to load integration" });
    }
    if (body.isActive === true && !row.isActive)
      await publishEvent("integration.sync_rules_changed", {
        projectId,
        integrationId: row.id,
      });
    await publishEvent("project.updated", { projectId, linksChanged: true });
    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 }, result.status ?? 400);
  }

  return c.json({ status: "success" });
}

export default gitlabIntegration;