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(sales): verify Paperless Parts webhook against raw request body (#1618)
Brad Barbin2dd6782cfe60
diff --git a/.ai/plans/2026-09-11-paperless-parts-webhook-401.md b/.ai/plans/2026-09-11-paperless-parts-webhook-401.mdnew file mode 100644index 0000000000..484bf2a633--- /dev/null+++ b/.ai/plans/2026-09-11-paperless-parts-webhook-401.md@@ -0,0 +1,8 @@+# Paperless Parts webhook 401 regression++- [x] Read repository guidance and inspect the customer screenshot.+- [x] Trace every 401 exit in the inbound webhook route and its secret-resolution dependencies.+- [x] Compare recent code/dependency/deployment-relevant changes with the last known working behavior.+- [x] Reproduce the signature verification behavior with focused tests or a local harness.+- [x] Implement the smallest root-cause fix, if the evidence supports one.+- [x] Run scoped verification and document the outcome.diff --git a/.ai/runs/2026-09-11-paperless-parts-webhook-401.md b/.ai/runs/2026-09-11-paperless-parts-webhook-401.mdnew file mode 100644index 0000000000..81dc26bfeb--- /dev/null+++ b/.ai/runs/2026-09-11-paperless-parts-webhook-401.md@@ -0,0 +1,24 @@+# Bugfix run: Paperless Parts webhook 401 regression++- Date: 2026-09-11+- Mode: fully-autonomous+- Request: "a customer tried syncing their quotes from paperless parts to carbon, and got a 401 error. this has worked in the past (as recently as a day ago)"+- Phase plan: root-cause [run] · instrument [skip — deterministic reproduction] · fix [run] · test [skip — regression test covers the pure signature logic] · commit [skip — not explicitly requested]++## Decisions++- Production probe: an unsigned POST to the reported company endpoint returned 401, proving the integration row and vaulted credentials resolve before signature verification.+- Runtime instrumentation: skipped — escaped-Unicode payload deterministically reproduces the HMAC mismatch locally.+- Browser test: skipped — this is a pure server-side signature check covered by the route regression test.+- Commit: skipped — not explicitly requested.++## Phase log++- root-cause: HIGH confidence in a deterministic raw-body corruption defect; MEDIUM-HIGH confidence it caused this exact incident. Brief: `.context/paperless-parts-webhook-401-root-cause.md`.+- fix: verified the HMAC against `request.text()` before parsing, retained the historical normalized fallback, and added non-sensitive rejection-category logging.+- regression: RED on unchanged code (`expected { success: true }`, received HTTP 401); GREEN after fix (3/3 Paperless tests).+- verification: webhook suite 11/11 PASS; Biome 2 files PASS; ERP typecheck PASS after generating missing React Router route types.++## Outcome++- READY — fix and regression coverage are complete; no commit or deployment was requested.diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.tsnew file mode 100644index 0000000000..fb769d2af0--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.test.ts@@ -0,0 +1,85 @@+import { createHmac } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";++const SECRET = "00112233445566778899aabbccddeeff";+const TIMESTAMP = 1_726_070_400;++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({})+}));+vi.mock("@carbon/ee", () => ({+ resolveIntegrationSecrets: () => ({ apiKey: "api-key", secretKey: SECRET })+}));+vi.mock("@carbon/jobs", () => ({ trigger: vi.fn() }));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })+}));+vi.mock("~/modules/settings/settings.service", () => ({+ getIntegration: () => ({+ data: { metadata: {}, secretRef: "secret-ref" },+ error: null+ })+}));++import { trigger } from "@carbon/jobs";+import { action } from "./webhook.paperless-parts.$companyId";++function signature(body: string) {+ return createHmac("sha256", Buffer.from(SECRET, "hex"))+ .update(`${TIMESTAMP}.${body}`)+ .digest("hex");+}++function run(+ body: string,+ options: { signedBody?: string; signature?: string } = {}+) {+ const request = new Request(+ "http://localhost/api/webhook/paperless-parts/company-1",+ {+ method: "POST",+ body,+ headers: {+ "Paperless-Parts-Signature": `t=${TIMESTAMP},v1=${+ options.signature ?? signature(options.signedBody ?? body)+ }`,+ "content-type": "application/json"+ }+ }+ );+ return action({ request, params: { companyId: "company-1" } } as never);+}++describe("Paperless Parts webhook signature verification", () => {+ beforeEach(() => {+ vi.mocked(trigger).mockReset();+ });++ it("verifies the exact signed body when Python escapes Unicode", async () => {+ const body =+ '{"type": "quote.sent", "data": {"quote_notes": "Caf\\u00e9"}}';++ expect(await run(body)).toEqual({ success: true });+ expect(trigger).toHaveBeenCalledOnce();+ });++ it("keeps accepting Paperless' historical normalized representation", async () => {+ const body = '{"type":"quote.sent","data":{"quote_notes":"ASCII"}}';+ const normalizedBody =+ '{"type": "quote.sent", "data": {"quote_notes": "ASCII"}}';++ expect(await run(body, { signedBody: normalizedBody })).toEqual({+ success: true+ });+ expect(trigger).toHaveBeenCalledOnce();+ });++ it("rejects an invalid signature without enqueueing the webhook", async () => {+ const result = (await run('{"type":"quote.sent","data":{}}', {+ signature: "0".repeat(64)+ })) as { init?: { status?: number } };++ expect(result.init?.status).toBe(401);+ expect(trigger).not.toHaveBeenCalled();+ });+});diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.tsindex 3014c8f6da..ca10a93d70 100644--- a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts@@ -30,6 +30,15 @@ function createHmacSignature(.digest("hex");}+function signaturesMatch(signature: string, expectedSignature: string) {+ const signatureBuffer = Buffer.from(signature);+ const expectedBuffer = Buffer.from(expectedSignature);+ return (+ signatureBuffer.length === expectedBuffer.length &&+ crypto.timingSafeEqual(signatureBuffer, expectedBuffer)+ );+}+export async function loader({ request, params }: LoaderFunctionArgs) {const { companyId } = params;if (!companyId) {@@ -70,10 +79,15 @@ export async function action({ request, params }: ActionFunctionArgs) {);const { apiKey, secretKey } = integrationValidator.parse(resolvedMetadata);- // The signature provided by Paperless Parts is computed using the Python json.dumps() function,- // which formats the JSON string with newlines and whitespace.- // We need to remove the newlines and whitespace to match the signature.- const payloadText = JSON.stringify(await request.json(), null, 1)+ // HMACs authenticate bytes, not parsed JSON. Paperless signs the serialized+ // request body, so preserve it exactly (including escapes and number syntax).+ const rawPayloadText = await request.text();+ const payload = JSON.parse(rawPayloadText);++ // Keep accepting the historical normalized representation for deliveries+ // where Paperless signed json.dumps(payload) but transmitted different+ // whitespace. New deliveries should match the raw body.+ const normalizedPayloadText = JSON.stringify(payload, null, 1).replace(/^ +/gm, " ").replace(/\n/g, "").replace(/{ /g, "{")@@ -85,37 +99,55 @@ export async function action({ request, params }: ActionFunctionArgs) {request.headers.get("paperless-parts-signature") ||request.headers.get("Paperless-Parts-Signature");if (!signatureHeader) {+ logger.warning("Paperless Parts webhook rejected", {+ companyId,+ reason: "missing_signature_header"+ });return data({ success: false }, { status: 401 });}// Parse timestamp and signature from headerconst [timestampPart, signaturePart] = signatureHeader.split(",");+ if (!timestampPart || !signaturePart) {+ logger.warning("Paperless Parts webhook rejected", {+ companyId,+ reason: "malformed_signature_header"+ });+ return data({ success: false }, { status: 401 });+ }const timestamp = Number(timestampPart.replace("t=", ""));const signature = signaturePart.replace("v1=", "");if (!timestamp || !signature) {+ logger.warning("Paperless Parts webhook rejected", {+ companyId,+ reason: "malformed_signature_header"+ });return data({ success: false }, { status: 401 });}- const expectedSignature = createHmacSignature(- payloadText,- secretKey,- timestamp- );-// Constant-time comparison (SC-13): a plain `!==` leaks, via timing, how many- // leading bytes of a forged signature are correct. Guard length first —- // timingSafeEqual throws on unequal-length buffers.- const signatureBuffer = Buffer.from(signature);- const expectedBuffer = Buffer.from(expectedSignature);+ // leading bytes of a forged signature are correct. Check both the exact+ // signed bytes and the legacy normalized representation for compatibility.+ const signedPayloadCandidates = new Set([+ rawPayloadText,+ normalizedPayloadText+ ]);if (- signatureBuffer.length !== expectedBuffer.length ||- !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)+ ![...signedPayloadCandidates].some((candidate) =>+ signaturesMatch(+ signature,+ createHmacSignature(candidate, secretKey, timestamp)+ )+ )) {+ logger.warning("Paperless Parts webhook rejected", {+ companyId,+ reason: "signature_mismatch"+ });return data({ success: false }, { status: 401 });}- const payload = JSON.parse(payloadText);logger.info("payload", payload);await trigger("paperless-parts", {