Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

13.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { createHmac, timingSafeEqual } from "node:crypto";
import { SLACK_SIGNING_SECRET } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import {
  AmbiguousSlackWorkspaceError,
  createSlackWebClient,
  getSlackWorkspaceByTeamId
} from "@carbon/ee/slack.server";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { z } from "zod";
import {
  getIssueTypesList,
  getIssueWorkflowsList
} from "~/modules/quality/quality.service";
import { shareLinkContext } from "~/modules/service-context.server";
import { createIssueFromSlack } from "~/modules/shared/shared.server";

// nodejs runtime: the Slack signature check uses node:crypto.
export const config = { runtime: "nodejs" };

const logger = getLogger("erp", "slack", "interactive");

const slackInteractivePayloadSchema = z.object({
  type: z.string(),
  team: z
    .object({
      id: z.string(),
      domain: z.string()
    })
    .optional(),
  user: z.object({
    id: z.string(),
    name: z.string().optional(),
    username: z.string().optional()
  }),
  channel: z
    .object({
      id: z.string(),
      name: z.string()
    })
    .optional(),
  trigger_id: z.string().optional(),
  response_url: z.string().optional(),
  actions: z.array(z.any()).optional(),
  view: z.any().optional(),
  api_app_id: z.string().optional(),
  token: z.string().optional(),
  container: z.any().optional(),
  enterprise: z.any().optional(),
  message: z.any().optional(),
  // Shortcut specific fields
  callback_id: z.string().optional()
});

const SLACK_SIGNATURE_VERSION = "v0";
const SLACK_MAX_REQUEST_AGE_SECONDS = 5 * 60;

/**
 * Verifies Slack's `x-slack-signature` HMAC over the RAW body. The payload's
 * `team.id` picks the company this request acts on with the service role, and a
 * Slack team id is not a secret — without this check anyone could POST a forged
 * payload and create issues in any company that has Slack connected.
 */
function isValidSlackSignature(request: Request, rawBody: string): boolean {
  if (!SLACK_SIGNING_SECRET) return false;

  const timestamp = request.headers.get("x-slack-request-timestamp");
  const signature = request.headers.get("x-slack-signature");
  if (!timestamp || !signature) return false;

  const timestampSeconds = Number.parseInt(timestamp, 10);
  if (
    !Number.isFinite(timestampSeconds) ||
    Math.abs(Date.now() / 1000 - timestampSeconds) >
      SLACK_MAX_REQUEST_AGE_SECONDS
  ) {
    return false;
  }

  const expected = `${SLACK_SIGNATURE_VERSION}=${createHmac(
    "sha256",
    SLACK_SIGNING_SECRET
  )
    .update(`${SLACK_SIGNATURE_VERSION}:${timestamp}:${rawBody}`)
    .digest("hex")}`;

  const a = Buffer.from(signature);
  const b = Buffer.from(expected);
  return a.length === b.length && timingSafeEqual(a, b);
}

export async function action({ request }: ActionFunctionArgs) {
  try {
    const rawBody = await request.text();

    if (!isValidSlackSignature(request, rawBody)) {
      logger.error(
        "Rejected Slack interactive request with invalid signature",
        {
          hasSigningSecret: Boolean(SLACK_SIGNING_SECRET)
        }
      );
      return data({ error: "Invalid signature" }, { status: 401 });
    }

    const payloadString = new URLSearchParams(rawBody).get("payload");

    if (!payloadString) {
      return data({ error: "Missing payload" }, { status: 400 });
    }

    let payload = slackInteractivePayloadSchema.safeParse(
      JSON.parse(payloadString)
    );

    if (!payload.success) {
      logger.error("Slack payload validation error", { error: payload.error });
      return data(
        {
          response_type: "ephemeral",
          text: "Invalid payload format received."
        },
        { status: 400 }
      );
    }

    const serviceRole = await getCarbonServiceRole();

    if (!payload.data.team?.id) {
      return {
        response_type: "ephemeral",
        text: "Invalid payload: missing team information."
      };
    }

    let workspace: Awaited<ReturnType<typeof getSlackWorkspaceByTeamId>>;
    try {
      workspace = await getSlackWorkspaceByTeamId(
        serviceRole,
        payload.data.team.id
      );
    } catch (err) {
      if (err instanceof AmbiguousSlackWorkspaceError) {
        logger.error("Slack workspace linked to more than one company", {
          teamId: payload.data.team.id
        });
        return {
          response_type: "ephemeral",
          text: "This Slack workspace is connected to more than one Carbon company, so Carbon cannot tell which one you mean. Ask an admin to disconnect it from all but one."
        };
      }
      throw err;
    }

    if (workspace === null) {
      logger.error("No Slack connection for workspace", {
        teamId: payload.data.team.id
      });
      return {
        response_type: "ephemeral",
        text: "Slack integration not found for this workspace."
      };
    }

    const { companyId, token: slackToken } = workspace;

    switch (payload.data.type) {
      case "shortcut":
        return handleShortcut(payload.data, companyId, slackToken, serviceRole);

      case "block_actions":
        return handleBlockActions(payload.data, companyId, slackToken);

      case "view_submission":
        return handleViewSubmission(payload.data, companyId);

      case "view_closed":
        return { ok: true };

      default:
        return {
          response_type: "ephemeral",
          text: `Unknown interaction type: ${payload.data.type}`
        };
    }
  } catch (error) {
    logger.error("Slack interactive error", { error });
    return data(
      {
        response_type: "ephemeral",
        text: "An error occurred processing your interaction. Please try again."
      },
      { status: 500 }
    );
  }
}

async function handleBlockActions(
  payload: z.infer<typeof slackInteractivePayloadSchema>,
  companyId: string,
  slackToken: string
) {
  const action = payload.actions?.[0];

  if (!action) {
    return { ok: true };
  }

  // Handle other block actions here as needed
  // Issue creation is now handled via shortcuts

  switch (action.action_id) {
    case "view_in_carbon":
      return { ok: true };

    default:
      return { ok: true };
  }
}

async function handleShortcut(
  payload: z.infer<typeof slackInteractivePayloadSchema>,
  companyId: string,
  slackToken: string,
  serviceRole: SupabaseClient<Database>
) {
  const callbackId = payload.callback_id;

  switch (callbackId) {
    case "create_ncr_modal":
      return handleCreateNcrShortcut(
        payload,
        companyId,
        slackToken,
        serviceRole
      );

    default:
      return { ok: true };
  }
}

async function handleCreateNcrShortcut(
  payload: z.infer<typeof slackInteractivePayloadSchema>,
  companyId: string,
  slackToken: string,
  serviceRole: any
) {
  if (!payload.trigger_id) {
    return {
      response_type: "ephemeral",
      text: "Missing trigger ID for modal interaction."
    };
  }

  try {
    const [types, workflows] = await Promise.all([
      getIssueTypesList(serviceRole, companyId),
      getIssueWorkflowsList(serviceRole, companyId)
    ]);

    const slackClient = createSlackWebClient({ token: slackToken });

    await slackClient.views.open({
      trigger_id: payload.trigger_id,
      view: {
        type: "modal",
        callback_id: "create_ncr_modal",
        title: {
          type: "plain_text",
          text: "Create Issue"
        },
        submit: {
          type: "plain_text",
          text: "Create"
        },
        close: {
          type: "plain_text",
          text: "Cancel"
        },
        blocks: [
          {
            type: "input",
            block_id: "title_block",
            label: {
              type: "plain_text",
              text: "Title"
            },
            element: {
              type: "plain_text_input",
              action_id: "title",
              placeholder: {
                type: "plain_text",
                text: "Brief description of the non-conformance"
              }
            }
          },
          {
            type: "input",
            block_id: "description_block",
            label: {
              type: "plain_text",
              text: "Description"
            },
            element: {
              type: "plain_text_input",
              action_id: "description",
              multiline: true,
              placeholder: {
                type: "plain_text",
                text: "Detailed description of the issue"
              }
            },
            optional: true
          },
          {
            type: "input",
            block_id: "type_block",
            label: {
              type: "plain_text",
              text: "Type"
            },
            element: {
              type: "static_select",
              action_id: "type",
              placeholder: {
                type: "plain_text",
                text: "Select issue type"
              },
              options:
                types.data?.map((type) => ({
                  text: {
                    type: "plain_text",
                    text: type.name
                  },
                  value: type.id
                })) || []
            }
          },
          // Only include workflow block if workflows are available
          ...(workflows.data && workflows.data.length > 0
            ? [
                {
                  type: "input" as const,
                  block_id: "workflow_block",
                  label: {
                    type: "plain_text" as const,
                    text: "Workflow"
                  },
                  element: {
                    type: "static_select" as const,
                    action_id: "workflow",
                    placeholder: {
                      type: "plain_text" as const,
                      text: "Select workflow"
                    },
                    options: workflows.data.map((workflow) => ({
                      text: {
                        type: "plain_text" as const,
                        text: workflow.name
                      },
                      value: workflow.id
                    }))
                  },
                  optional: true
                }
              ]
            : []),
          {
            type: "input",
            block_id: "severity_block",
            label: {
              type: "plain_text",
              text: "Severity"
            },
            element: {
              type: "static_select",
              action_id: "severity",
              placeholder: {
                type: "plain_text",
                text: "Select severity"
              },
              options: [
                { text: { type: "plain_text", text: "Low" }, value: "Low" },
                {
                  text: { type: "plain_text", text: "Medium" },
                  value: "Medium"
                },
                { text: { type: "plain_text", text: "High" }, value: "High" },
                {
                  text: { type: "plain_text", text: "Critical" },
                  value: "Critical"
                }
              ]
            },
            optional: true
          }
        ],
        private_metadata: JSON.stringify({
          channel_id: payload.channel?.id || "",
          user_id: payload.user.id
        })
      }
    });

    return { ok: true };
  } catch (error) {
    logger.error("Error opening Issue modal", { error });
    return {
      response_type: "ephemeral",
      text: "Failed to open Issue form. Please try again."
    };
  }
}

async function handleViewSubmission(
  payload: z.infer<typeof slackInteractivePayloadSchema>,
  companyId: string
) {
  const view = payload.view;

  if (view.callback_id !== "create_ncr_modal") {
    return { ok: true };
  }

  const failed = {
    response_action: "errors",
    errors: {
      title_block: "Failed to create Issue. Please try again."
    }
  };

  try {
    const values = view.state.values;
    const { user_id } = JSON.parse(view.private_metadata);

    // The verified signature is the only credential: the workspace's company
    // is the one acted in.
    const ctx = await shareLinkContext({ companyId, createdBy: "system" });
    if (!ctx) throw new Error("Failed to read the company");

    const created = await createIssueFromSlack(ctx, {
      slackUserId: user_id,
      title: values.title_block.title.value,
      description: values.description_block?.description?.value || "",
      nonConformanceTypeId: values.type_block.type.selected_option?.value,
      nonConformanceWorkflowId:
        values.workflow_block?.workflow?.selected_option?.value,
      priority:
        values.severity_block?.severity?.selected_option?.value || "Medium"
    });
    if (created.error) {
      logger.error("Error creating Issue", { error: created.error });
      return failed;
    }

    return {
      response_action: "clear"
    };
  } catch (error) {
    logger.error("Error creating Issue", { error });
    return failed;
  }
}