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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(suggestions): harden Carbon Slack forwarding (trust, gating, bounded retries)
naveenkashc2d21bd93720
diff --git a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx b/apps/erp/app/components/Layout/Topbar/Suggestion.tsxindex a9662cec7b..14f0651899 100644--- a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx+++ b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx@@ -1,4 +1,4 @@-import { useCarbon } from "@carbon/auth";+import { CARBON_SLACK_ENABLED, useCarbon } from "@carbon/auth";import {Hidden,Submit,@@ -54,7 +54,7 @@ const Suggestion = () => {const [emoji, setEmoji] = useState(defaultEmoji);const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);const [anonymous, setAnonymous] = useState(true);- const [sendToCarbon, setSendToCarbon] = useState(true);+ const [sendToCarbon, setSendToCarbon] = useState(CARBON_SLACK_ENABLED);const mode = useMode();const pickerTheme = mode;const [attachment, setAttachment] = useState<{@@ -72,7 +72,7 @@ const Suggestion = () => {setEmoji(defaultEmoji);setAttachment(null);setAnonymous(true);- setSendToCarbon(true);+ setSendToCarbon(CARBON_SLACK_ENABLED);popoverTriggerRef.current?.click();} else if (fetcher.data?.message) {toast.error(fetcher.data.message);@@ -171,17 +171,19 @@ const Suggestion = () => {<Trans>Submit anonymously</Trans></span></HStack>- <HStack spacing={2}>- <Checkbox- isChecked={sendToCarbon}- onCheckedChange={(checked) =>- setSendToCarbon(checked === true)- }- />- <span className="text-sm">- <Trans>Send to Carbon</Trans>- </span>- </HStack>+ {CARBON_SLACK_ENABLED && (+ <HStack spacing={2}>+ <Checkbox+ isChecked={sendToCarbon}+ onCheckedChange={(checked) =>+ setSendToCarbon(checked === true)+ }+ />+ <span className="text-sm">+ <Trans>Send to Carbon</Trans>+ </span>+ </HStack>+ )}</VStack><Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}><PopoverTrigger asChild>diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex 25bb5e412a..a8a5d13061 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -102,6 +102,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {AUTH_PROVIDERS,CARBON_EDITION,CARBON_API_URL,+ CARBON_SLACK_ENABLED,CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT,ERP_URL,@@ -132,6 +133,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {AUTH_PROVIDERS,CARBON_API_URL,CARBON_EDITION,+ CARBON_SLACK_ENABLED,CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT,DEFAULT_LANGUAGE,diff --git a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx b/apps/erp/app/routes/x+/resources+/suggestions.new.tsxindex 204791d26c..59e5b11140 100644--- a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx+++ b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx@@ -32,6 +32,16 @@ export async function action({ request }: ActionFunctionArgs) {userId: formUserId,sendToCarbon} = validation.data;++ // Never trust form-supplied identifiers: the userId field is only an+ // anonymous on/off signal (attribute the authenticated user or nobody), and+ // attachments must live in this company's suggestions folder.+ const suggestionUserId = formUserId ? userId : null;+ const suggestionAttachmentPath =+ attachmentPath && attachmentPath.startsWith(`${companyId}/suggestions/`)+ ? attachmentPath+ : null;+const serviceRole = await getCarbonServiceRole();const insertSuggestion = await serviceRole@@ -41,8 +51,8 @@ export async function action({ request }: ActionFunctionArgs) {suggestion,emoji,path,- attachmentPath: attachmentPath || null,- userId: formUserId || null,+ attachmentPath: suggestionAttachmentPath,+ userId: suggestionUserId,companyId}])@@ -65,8 +75,8 @@ export async function action({ request }: ActionFunctionArgs) {suggestion,emoji,path,- userId: formUserId,- attachmentPath+ userId: suggestionUserId,+ attachmentPath: suggestionAttachmentPath});}@@ -80,7 +90,7 @@ export async function action({ request }: ActionFunctionArgs) {type: "group",groupIds: company.data.suggestionNotificationGroup},- from: formUserId || userId+ from: suggestionUserId || userId});} catch (err) {logger.error("Failed to trigger suggestion notification", { error: err });diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsxindex 69a0f6fb81..e1663a8f16 100644--- a/apps/mes/app/components/Suggestion.tsx+++ b/apps/mes/app/components/Suggestion.tsx@@ -1,4 +1,4 @@-import { useCarbon } from "@carbon/auth";+import { CARBON_SLACK_ENABLED, useCarbon } from "@carbon/auth";import {Hidden,Submit,@@ -53,7 +53,7 @@ const Suggestion = () => {const [emoji, setEmoji] = useState("💡");const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);const [anonymous, setAnonymous] = useState(true);- const [sendToCarbon, setSendToCarbon] = useState(true);+ const [sendToCarbon, setSendToCarbon] = useState(CARBON_SLACK_ENABLED);const mode = useMode();const pickerTheme = mode;const [attachment, setAttachment] = useState<{@@ -72,7 +72,7 @@ const Suggestion = () => {setEmoji("💡");setAttachment(null);setAnonymous(true);- setSendToCarbon(true);+ setSendToCarbon(CARBON_SLACK_ENABLED);popoverTriggerRef.current?.click();} else if (fetcher.data?.message) {toast.error(fetcher.data.message);@@ -172,17 +172,19 @@ const Suggestion = () => {<Trans>Submit anonymously</Trans></span></HStack>- <HStack spacing={2}>- <Checkbox- isChecked={sendToCarbon}- onCheckedChange={(checked) =>- setSendToCarbon(checked === true)- }- />- <span className="text-sm">- <Trans>Send to Carbon</Trans>- </span>- </HStack>+ {CARBON_SLACK_ENABLED && (+ <HStack spacing={2}>+ <Checkbox+ isChecked={sendToCarbon}+ onCheckedChange={(checked) =>+ setSendToCarbon(checked === true)+ }+ />+ <span className="text-sm">+ <Trans>Send to Carbon</Trans>+ </span>+ </HStack>+ )}</VStack><Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}><PopoverTrigger asChild>diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 0f60142a0c..fe0c2762cd 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -94,6 +94,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {AUTH_PROVIDERS,CARBON_EDITION,CARBON_API_URL,+ CARBON_SLACK_ENABLED,CONTROLLED_ENVIRONMENT,ERP_URL,LOG_LEVEL,@@ -117,6 +118,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {AUTH_PROVIDERS,CARBON_EDITION,CARBON_API_URL,+ CARBON_SLACK_ENABLED,CONTROLLED_ENVIRONMENT,ERP_URL,LOG_LEVEL,diff --git a/apps/mes/app/routes/x+/suggestion.tsx b/apps/mes/app/routes/x+/suggestion.tsxindex 7262cf658d..2454b6441f 100644--- a/apps/mes/app/routes/x+/suggestion.tsx+++ b/apps/mes/app/routes/x+/suggestion.tsx@@ -31,6 +31,16 @@ export async function action({ request }: ActionFunctionArgs) {userId: formUserId,sendToCarbon} = validation.data;++ // Never trust form-supplied identifiers: the userId field is only an+ // anonymous on/off signal (attribute the authenticated user or nobody), and+ // attachments must live in this company's suggestions folder.+ const suggestionUserId = formUserId ? userId : null;+ const suggestionAttachmentPath =+ attachmentPath && attachmentPath.startsWith(`${companyId}/suggestions/`)+ ? attachmentPath+ : null;+const serviceRole = await getCarbonServiceRole();const insertSuggestion = await serviceRole@@ -40,8 +50,8 @@ export async function action({ request }: ActionFunctionArgs) {suggestion,emoji,path,- attachmentPath: attachmentPath || null,- userId: formUserId || null,+ attachmentPath: suggestionAttachmentPath,+ userId: suggestionUserId,companyId}])@@ -68,8 +78,8 @@ export async function action({ request }: ActionFunctionArgs) {suggestion,emoji,path,- userId: formUserId,- attachmentPath+ userId: suggestionUserId,+ attachmentPath: suggestionAttachmentPath});}@@ -83,7 +93,7 @@ export async function action({ request }: ActionFunctionArgs) {type: "group",groupIds: company.data.suggestionNotificationGroup},- from: formUserId || userId+ from: suggestionUserId || userId});} catch (err) {log.error("Failed to trigger suggestion notification", { error: err });diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 7af0581f79..6e8c14deeb 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -7,6 +7,7 @@ declare global {AUTH_PROVIDERS: string;CARBON_EDITION: string;CARBON_API_URL: string;+ CARBON_SLACK_ENABLED: string;CLOUDFLARE_TURNSTILE_SITE_KEY: string;CONTROLLED_ENVIRONMENT: string;ERP_URL: string;@@ -247,6 +248,12 @@ export const RESEND_DOMAIN =export const SLACK_BOT_TOKEN = getEnv("SLACK_BOT_TOKEN", {isRequired: false});+// Derived, non-secret flag telling the browser whether this deployment can+// forward suggestions to Carbon's Slack — the token itself stays server-only.+// Crosses the wire as "true" | "" (window.env values are all strings).+export const CARBON_SLACK_ENABLED = isBrowser+ ? window.env?.CARBON_SLACK_ENABLED === "true"+ : Boolean(SLACK_BOT_TOKEN);export const SLACK_CLIENT_ID = getEnv("SLACK_CLIENT_ID", {isRequired: false});@@ -436,6 +443,7 @@ export function getBrowserEnv() {AUTH_PROVIDERS,CARBON_API_URL,CARBON_EDITION,+ CARBON_SLACK_ENABLED: CARBON_SLACK_ENABLED ? "true" : "",CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT,DEFAULT_LANGUAGE,diff --git a/packages/lib/src/slack.server.ts b/packages/lib/src/slack.server.tsindex 543e5579e7..26bdf7ba8a 100644--- a/packages/lib/src/slack.server.ts+++ b/packages/lib/src/slack.server.ts@@ -1,6 +1,7 @@import type { Database } from "@carbon/database";import { getAppUrl, SLACK_BOT_TOKEN } from "@carbon/env";import { getLogger } from "@carbon/logger";+import type { WebClientOptions } from "@slack/web-api";import { WebClient } from "@slack/web-api";import type { SupabaseClient } from "@supabase/supabase-js";@@ -15,8 +16,8 @@ interface SlackMessage {class SlackClient {private client: WebClient;- constructor(token: string) {- this.client = new WebClient(token);+ constructor(token: string, options?: WebClientOptions) {+ this.client = new WebClient(token, options);}async sendMessage({ channel, text, blocks }: SlackMessage): Promise<void> {@@ -36,9 +37,13 @@ class SlackClient {}}-export function getSlackClient(token?: string): SlackClient {+export function getSlackClient(+ token?: string,+ options?: WebClientOptions+): SlackClient {return new SlackClient(- token ?? process.env.SLACK_BOT_TOKEN ?? SLACK_BOT_TOKEN ?? ""+ token ?? process.env.SLACK_BOT_TOKEN ?? SLACK_BOT_TOKEN ?? "",+ options);}@@ -55,6 +60,10 @@ function escapeSlackText(text: string): string {.replace(/>/g, ">");}+// Operates on already-escaped text so SECTION_CHAR_LIMIT bounds the exact+// length Slack receives. Escaped entities (& / < / >) contain no+// whitespace, so only a hard cut can land inside one — back up to keep the+// entity intact.function splitForSections(text: string): string[] {const chunks: string[] = [];let start = 0;@@ -64,7 +73,14 @@ function splitForSections(text: string): string[] {const newline = text.lastIndexOf("\n", end);const space = text.lastIndexOf(" ", end);const breakAt = Math.max(newline, space);- if (breakAt > start) end = breakAt;+ if (breakAt > start) {+ end = breakAt;+ } else {+ const amp = text.lastIndexOf("&", end - 1);+ if (amp > start && !text.slice(amp, end).includes(";")) {+ end = amp;+ }+ }}chunks.push(text.slice(start, end));start = end;@@ -89,6 +105,11 @@ export async function postSuggestionToCarbonSlack(attachmentPath?: string | null;}): Promise<void> {+ // Self-hosted deployments have no Carbon Slack token — nothing to post to,+ // even if a forged form submits sendToCarbon=true.+ if (!(process.env.SLACK_BOT_TOKEN ?? SLACK_BOT_TOKEN)) {+ return;+ }try {const [user, attachmentUrl] = await Promise.all([input.userId@@ -128,7 +149,12 @@ export async function postSuggestionToCarbonSlack(});}- await getSlackClient().sendMessage({+ // This is awaited inside the user's submit request — the WebClient default+ // retry policy (ten retries over ~30 minutes on 5xx/429) would hang the+ // response during a Slack outage. One attempt, then give up.+ await getSlackClient(undefined, {+ retryConfig: { retries: 0 }+ }).sendMessage({channel: SUGGESTION_CHANNEL,text: `New suggestion from ${companyName}`,blocks: [