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: sanitize MES step-record upload filenames; (#1212)
Anshul sharma60952f7158f0
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex d85ecb385f..5cc757d46d 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -487,3 +487,13 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** Don't rely on `debounce` for Carbon Inngest functions validated against the local dev server — it's broken there. For the event queue the coalescing was moved upstream: `dispatch_event_batch()` wakes at most once per transaction (txn-local GUC `carbon.event_wake_sent`), so the important bulk case (a CSV import = one transaction) is already one wake; `concurrency: 1` + loop-until-empty drain absorbs the rest (extra runs from many separate transactions are cheap no-ops that read an empty queue). If you must coalesce many *separate* transactions in a burst, do it at the DB/application layer, not with `debounce`. Verify any flow-control choice by watching `docker logs <inngest container>` for `error handling queue item` during a burst, not just by trusting the config.**Applies to:** `packages/jobs/src/inngest/functions/events/queue.ts`; any new Inngest function reaching for `debounce`/flow-control that will be exercised in local dev.++## Storage keys built from raw filenames break silently — always sanitize, and the portal share route regex is a hidden contract with every upload path shape++**Context:** MES file/inspection step uploads (`RecordModal` in `apps/mes/app/components/JobOperation/components/Step.tsx`) put the raw `file.name` into the Supabase storage key. macOS screenshot names contain U+202F (narrow no-break space before "AM/PM"), which is outside Supabase storage's allowed-key charset.++**Problem:** The upload fails with "Invalid key", but the modal had already rendered the file card (`setFile` before the await), so the operator saw the file "attached" with the Record button permanently disabled — no actionable error. Separately, the customer-portal file route (`share+/customer.$id.$.tsx`) validated paths with a regex hardcoded to the *old* flat layout `companyId/job/operationId/file`; when `032f8d0e` nested step uploads under `/stepId/nanoid/`, every portal file link started returning 403 and nobody noticed for months.++**Rule:** (1) Any storage key that embeds a user-controlled filename must pass it through `stripSpecialCharacters` (canonical copy in `@carbon/utils`, re-exported by `~/utils/string` in ERP) with a `|| "file"` fallback for names that sanitize to empty. (2) The share-route path validation (`parseJobFilePath` in `apps/erp/app/utils/supabase.ts`, unit-tested) is coupled to every writer of the `companyId/job/...` prefix — changing an upload path shape requires updating the parser and its test in the same PR. (3) On upload failure, reset the picker UI so the user can retry; never leave a dead-end state.++**Applies to:** all `storage.from(...).upload(...)` call sites in `apps/mes` and `apps/erp`; `share+/customer.$id.$.tsx`; any new externally-shared file route.diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.mdindex 6698eb6872..1c3c98641e 100644--- a/.claude/rules/mes-job-operation-ui.md+++ b/.claude/rules/mes-job-operation-ui.md@@ -48,7 +48,11 @@ steps/parameters, files, serials, and scrap/rework/finish actions.**mobile-only** job/customer/deadline info in a `md:hidden` block (the header hidesthat info on mobile).- **`components/Step.tsx`** — exports `StepsListItem`, **`RecordModal`**, and- **`DeleteStepRecordModal`** (these are NOT separate files).+ **`DeleteStepRecordModal`** (these are NOT separate files). File/Inspection step+ uploads go to the private bucket at+ `{companyId}/job/{operationId}/{stepId}/{nanoid}/{sanitized filename}` — this+ shape is a contract with `parseJobFilePath`+ (`apps/erp/app/utils/supabase.ts`), which gates the customer-portal file route.- **`components/Parameter.tsx`** — exports `ParametersListItem`.- Modals/sections: `IssueMaterialModal`, `QuantityModal` (type `scrap`/`finish`),`ReworkModal`, `SerialSelectorModal`, `QualityIssueModal`, `MaintenanceDispatch`,diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsxindex b4498a4ea5..e4704fa2b6 100644--- a/apps/erp/app/routes/share+/customer.$id.$.tsx+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx@@ -6,6 +6,7 @@ import { supportedModelTypes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { getJobByOperationId } from "~/modules/production";import { getCustomerPortal } from "~/modules/shared/shared.service";+import { parseJobFilePath } from "~/utils/supabase";const supportedFileTypes: Record<string, string> = {pdf: "application/pdf",@@ -84,19 +85,15 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {path = decodeURIComponent(path);- const pathMatch = params["*"]?.match(/^([^/]+)\/job\/([^/]+)\/[^/]+$/);- const companyId = pathMatch?.[1];- const operationId = pathMatch?.[2];+ const jobFile = parseJobFilePath(path);const fileType = path.split(".").pop()?.toLowerCase();- if (companyId !== customer.data.companyId) {+ if (!jobFile || jobFile.companyId !== customer.data.companyId) {return new Response(null, { status: 403 });}- if (!operationId) {- return new Response(null, { status: 403 });- }+ const { operationId } = jobFile;const job = await getJobByOperationId(serviceRole, operationId);@@ -121,10 +118,6 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {throw new Error(`File type ${fileType} not supported`);const contentType = supportedFileTypes[fileType];- if (!path.includes(customer.data.companyId)) {- return new Response(null, { status: 403 });- }-async function downloadFile() {const result = await serviceRole.storage.from(bucket!).download(`${path}`);if (result.error) {diff --git a/apps/erp/app/utils/string.ts b/apps/erp/app/utils/string.tsindex d111ac8e8d..31bb477ba5 100644--- a/apps/erp/app/utils/string.ts+++ b/apps/erp/app/utils/string.ts@@ -1,5 +1,7 @@import { getLogger } from "@carbon/logger";+export { stripSpecialCharacters } from "@carbon/utils";+const logger = getLogger("erp", "utils", "string");export const capitalize = (words: string) => {@@ -7,11 +9,6 @@ export const capitalize = (words: string) => {return [first.toLocaleUpperCase(), ...otherLetters].join("");};-export function stripSpecialCharacters(inputString: string) {- // Keep only characters that are valid for S3 keys- return inputString?.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,?]/g, "");-}-export const snakeToCamel = (str: string) =>str.replace(/([-_][a-z])/g, (group: string) =>group.toUpperCase().replace("-", "").replace("_", "")diff --git a/apps/erp/app/utils/supabase.test.ts b/apps/erp/app/utils/supabase.test.tsnew file mode 100644index 0000000000..5d8dc74259--- /dev/null+++ b/apps/erp/app/utils/supabase.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { parseJobFilePath } from "./supabase";++describe("parseJobFilePath", () => {+ it("parses the legacy flat path", () => {+ expect(parseJobFilePath("co123/job/op456/photo.png")).toEqual({+ companyId: "co123",+ operationId: "op456"+ });+ });++ it("parses the nested step-record path", () => {+ expect(+ parseJobFilePath(+ "co123/job/op456/step789/aBcD-123/Screenshot 2026-07-23 at 12.37.45 AM.png"+ )+ ).toEqual({+ companyId: "co123",+ operationId: "op456"+ });+ });++ it("rejects non-job paths", () => {+ expect(parseJobFilePath("co123/parts/item1/file.png")).toBeNull();+ });++ it("rejects paths without a file segment", () => {+ expect(parseJobFilePath("co123/job/op456")).toBeNull();+ expect(parseJobFilePath("co123/job/op456/")).toBeNull();+ });++ it("rejects empty segments", () => {+ expect(parseJobFilePath("co123/job/op456//file.png")).toBeNull();+ expect(parseJobFilePath("/job/op456/file.png")).toBeNull();+ });++ it("rejects depths other than the two known layouts", () => {+ expect(parseJobFilePath("co123/job/op456/extra/file.png")).toBeNull();+ expect(parseJobFilePath("co123/job/op456/a/b/c/file.png")).toBeNull();+ });++ it("rejects dot segments", () => {+ expect(parseJobFilePath("co123/job/op456/../op789/file.png")).toBeNull();+ expect(parseJobFilePath("co123/job/op456/./x/file.png")).toBeNull();+ });++ it("rejects empty and undefined input", () => {+ expect(parseJobFilePath(undefined)).toBeNull();+ expect(parseJobFilePath("")).toBeNull();+ });+});diff --git a/apps/erp/app/utils/supabase.ts b/apps/erp/app/utils/supabase.tsindex f7e49b9994..90b7aa6d04 100644--- a/apps/erp/app/utils/supabase.ts+++ b/apps/erp/app/utils/supabase.ts@@ -1 +1,18 @@export { sanitize } from "@carbon/utils";++/**+ * Parses a private-bucket job file path. Supports both layouts:+ * - legacy flat: {companyId}/job/{operationId}/{file}+ * - step records: {companyId}/job/{operationId}/{stepId}/{nanoid}/{file}+ */+export function parseJobFilePath(+ path: string | undefined+): { companyId: string; operationId: string } | null {+ if (!path) return null;+ const [companyId, kind, operationId, ...rest] = path.split("/");+ if (kind !== "job" || !companyId || !operationId) return null;+ if (rest.length !== 1 && rest.length !== 3) return null;+ if (rest.some((segment) => !segment || segment === "." || segment === ".."))+ return null;+ return { companyId, operationId };+}diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsxindex c8e9040991..f7ed0eb26f 100644--- a/apps/mes/app/components/JobOperation/components/Step.tsx+++ b/apps/mes/app/components/JobOperation/components/Step.tsx@@ -33,11 +33,14 @@ import {useDisclosure,VStack} from "@carbon/react";-import { parseMentionsFromDocument } from "@carbon/utils";+import {+ parseMentionsFromDocument,+ stripSpecialCharacters+} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import { nanoid } from "nanoid";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {LuChevronDown,LuChevronRight,@@ -372,16 +375,26 @@ export function RecordModal({const { company } = useUser();const [file, setFile] = useState<File | null>(null);const [filePath, setFilePath] = useState<string | null>(null);+ // Bumped on every drop/remove so a stale in-flight upload can't set state+ const uploadIdRef = useRef(0);const fetcher = useFetcher<{ success: boolean }>();+ const removeFile = () => {+ uploadIdRef.current += 1;+ setFile(null);+ setFilePath(null);+ };+const onDrop = async (acceptedFiles: File[]) => {if (!acceptedFiles[0] || !carbon) return;const fileUpload = acceptedFiles[0];+ const uploadId = ++uploadIdRef.current;setFile(fileUpload);toast.info(t`Uploading ${fileUpload.name}`);- const fileName = `${company.id}/job/${attribute.operationId}/${attribute.id}/${nanoid()}/${fileUpload.name}`;+ const safeName = stripSpecialCharacters(fileUpload.name) || "file";+ const fileName = `${company.id}/job/${attribute.operationId}/${attribute.id}/${nanoid()}/${safeName}`;const upload = await carbon?.storage.from("private")@@ -390,8 +403,11 @@ export function RecordModal({upsert: true});+ if (uploadIdRef.current !== uploadId) return;+if (upload.error) {toast.error(t`Failed to upload file: ${fileUpload.name}`);+ removeFile();} else if (upload.data?.path) {toast.success(t`Uploaded: ${fileUpload.name}`);setFilePath(upload.data.path);@@ -514,14 +530,7 @@ export function RecordModal({<div className="flex flex-col gap-2 items-center justify-center py-6 w-full"><LuFile className="size-10 text-muted-foreground" /><p className="text-sm text-muted-foreground">{file.name}</p>- <Button- variant="secondary"- size="sm"- onClick={() => {- setFile(null);- setFilePath(null);- }}- >+ <Button variant="secondary" size="sm" onClick={removeFile}><Trans>Remove</Trans></Button></div>@@ -539,10 +548,7 @@ export function RecordModal({<Buttonvariant="secondary"size="sm"- onClick={() => {- setFile(null);- setFilePath(null);- }}+ onClick={removeFile}>Remove</Button>diff --git a/packages/utils/src/string.ts b/packages/utils/src/string.tsindex 824ae088ce..0f4562c85d 100644--- a/packages/utils/src/string.ts+++ b/packages/utils/src/string.ts@@ -36,3 +36,8 @@ export function pluralize(): string {return count === 1 ? singular : (plural ?? `${singular}s`);}++export function stripSpecialCharacters(inputString: string) {+ // Keep only characters that are valid for S3 keys+ return inputString?.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,?]/g, "");+}