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(logger): mask redacted log fields instead of deleting them, keep ERP data visible
Sidwebworksc4106ef2ff6a
diff --git a/packages/logger/AGENTS.md b/packages/logger/AGENTS.mdindex 7f2489cd2d..a4dbad0f72 100644--- a/packages/logger/AGENTS.md+++ b/packages/logger/AGENTS.md@@ -37,9 +37,13 @@ categories, env-driven levels, and cloud-agnostic request-id correlation.parse). It covers `POST/PUT/PATCH/DELETE` with `application/json` or`application/x-www-form-urlencoded` bodies at/under 8KB (`content-length`required); multipart uploads, oversized, and unknown-length bodies log a short- marker instead. Sensitive fields (`password`/`token`/`secret`/`email`/… — the- `DEFAULT_REDACT_FIELDS` set) are masked `[REDACTED]` in the captured object.- The body is read from a clone, so the route handler's stream stays intact.+ marker instead. Sensitive fields (`password`/`token`/`secret`/… — the+ `REDACT_FIELD_PATTERNS` set in `src/redaction.ts`) are masked `[REDACTED]` in+ the captured object. That set is LogTape's `DEFAULT_REDACT_FIELDS` minus+ `email`/`phone`/`address` — ordinary ERP business data stays visible, and the+ prod sink MASKS matched fields rather than deleting them (a deleted key once+ made a PGRST204 failure unreconstructable from the log line). The body is read+ from a clone, so the route handler's stream stays intact.## Ask Firstdiff --git a/packages/logger/src/config.server.ts b/packages/logger/src/config.server.tsindex 5c9f867c23..4667dfc734 100644--- a/packages/logger/src/config.server.ts+++ b/packages/logger/src/config.server.ts@@ -10,6 +10,7 @@ import { readEnv } from "./env";import { httpDevFormatter } from "./http-formatter";import { type CarbonLogLevel, resolveLevel } from "./levels";import { CARBON_ROOT_CATEGORY } from "./logger";+import { maskRedactedField, REDACT_FIELD_PATTERNS } from "./redaction";const CONFIGURED = Symbol.for("carbon.logging.configured");@@ -42,8 +43,14 @@ export function ensureLoggingConfigured(const formatter = pretty ? ansiColorFormatter : getJsonLinesFormatter();const consoleSink = getConsoleSink({ formatter });// Redact sensitive field names (password, token, secret, …) before records- // reach the sink. Cheap: matches field names, not values.- const sink = pretty ? consoleSink : redactByField(consoleSink);+ // reach the sink. Cheap: matches field names, not values. Masks rather than+ // deletes, and skips email/phone/address — see ./redaction.ts.+ const sink = pretty+ ? consoleSink+ : redactByField(consoleSink, {+ fieldPatterns: REDACT_FIELD_PATTERNS,+ action: maskRedactedField+ });// HTTP access logs (`requestIdMiddleware`) get their own sink: a Morgan// "dev"-style colored line in dev, the same structured+redacted sink asdiff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.tsindex 85385cf457..d8f3a468dc 100644--- a/packages/logger/src/middleware.server.ts+++ b/packages/logger/src/middleware.server.ts@@ -1,5 +1,4 @@import { withContext } from "@logtape/logtape";-import { DEFAULT_REDACT_FIELDS } from "@logtape/redaction";import { createId } from "@paralleldrive/cuid2";import {createContext,@@ -7,6 +6,7 @@ import {type RouterContextProvider} from "react-router";import { getRequestContext } from "./context.server";+import { isSensitiveKey, REDACTED } from "./redaction";// Re-exported from the existing entry point rather than adding a new package// export subpath: Vite resolves a package's `exports` map once at dev-server@@ -34,16 +34,6 @@ const BODY_LOG_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);* pulled into the log path.*/const BODY_LOG_MAX_BYTES = 8 * 1024;-const REDACTED = "[REDACTED]";--/** `DEFAULT_REDACT_FIELDS` entries are `string | RegExp`; match either form. */-function isSensitiveKey(key: string): boolean {- return DEFAULT_REDACT_FIELDS.some((pattern) =>- typeof pattern === "string"- ? key.toLowerCase().includes(pattern.toLowerCase())- : pattern.test(key)- );-}/*** Mask sensitive query-param values (`?code=…`, `?token=…`, …) while keeping the@@ -64,10 +54,10 @@ function redactSearch(search: string): string {/*** Recursively mask values whose key matches a sensitive-field pattern (the same- * `DEFAULT_REDACT_FIELDS` LogTape's `redactByField` uses: password/token/secret/- * key/auth/email/phone/address/…). The sink-level redactor only runs in prod- * (JSONL); debug bodies are captured in dev where it's off, so we redact the- * body value here directly.+ * `REDACT_FIELD_PATTERNS` the prod sink's `redactByField` uses: password/token/+ * secret/key/auth/…). The sink-level redactor only runs in prod (JSONL); debug+ * bodies are captured in dev where it's off, so we redact the body value here+ * directly.*/function redactBody(value: unknown): unknown {if (Array.isArray(value)) return value.map(redactBody);diff --git a/packages/logger/src/middleware.test.ts b/packages/logger/src/middleware.test.tsindex 133682c02d..307752097f 100644--- a/packages/logger/src/middleware.test.ts+++ b/packages/logger/src/middleware.test.ts@@ -139,7 +139,9 @@ describe("requestIdMiddleware body logging", () => {});it("captures a form-urlencoded body and redacts sensitive fields", async () => {- const body = "email=a%40b.com¬e=hi";+ // email/phone/address are ordinary ERP business data and stay visible —+ // hiding them made real request payloads unreconstructable from logs.+ const body = "email=a%40b.com&apiToken=t0p¬e=hi";const request = new Request("http://x/action", {method: "POST",body,@@ -153,7 +155,8 @@ describe("requestIdMiddleware body logging", () => {async () => new Response("ok"));const captured = httpRecord()?.properties.body as Record<string, unknown>;- expect(captured.email).toBe("[REDACTED]");+ expect(captured.email).toBe("[email protected]");+ expect(captured.apiToken).toBe("[REDACTED]");expect(captured.note).toBe("hi");});diff --git a/packages/logger/src/redaction.test.ts b/packages/logger/src/redaction.test.tsnew file mode 100644index 0000000000..578ca6d5c5--- /dev/null+++ b/packages/logger/src/redaction.test.ts@@ -0,0 +1,62 @@+import type { LogRecord, Sink } from "@logtape/logtape";+import { redactByField } from "@logtape/redaction";+import { describe, expect, it } from "vitest";+import {+ isSensitiveKey,+ maskRedactedField,+ REDACT_FIELD_PATTERNS,+ REDACTED+} from "./redaction";++function makeRecord(properties: Record<string, unknown>): LogRecord {+ return {+ category: ["carbon", "test"],+ level: "info",+ message: ["msg"],+ rawMessage: "msg",+ timestamp: 0,+ properties+ };+}++describe("REDACT_FIELD_PATTERNS", () => {+ it("keeps the secret-class patterns and drops email/phone/address", () => {+ expect(isSensitiveKey("password")).toBe(true);+ expect(isSensitiveKey("apiToken")).toBe(true);+ expect(isSensitiveKey("clientSecret")).toBe(true);+ // Ordinary ERP business data must stay visible in logs — a hidden `phone`+ // key once made a PGRST204 failure unreconstructable from the log line.+ expect(isSensitiveKey("phone")).toBe(false);+ expect(isSensitiveKey("workPhone")).toBe(false);+ expect(isSensitiveKey("email")).toBe(false);+ expect(isSensitiveKey("addressLine1")).toBe(false);+ });+});++describe("prod sink redaction (redactByField wiring)", () => {+ const captured: LogRecord[] = [];+ const sink: Sink = redactByField((record) => captured.push(record), {+ fieldPatterns: REDACT_FIELD_PATTERNS,+ action: maskRedactedField+ });++ it("masks matched fields instead of deleting them, nested included", () => {+ captured.length = 0;+ sink(+ makeRecord({+ arguments: {+ contact: { firstName: "A", phone: "555", token: "t0p" }+ }+ })+ );+ expect(captured).toHaveLength(1);+ const args = captured[0]!.properties.arguments as {+ contact: Record<string, unknown>;+ };+ // The key survives with a visible marker — a deleted key is+ // indistinguishable from one the caller never sent.+ expect(args.contact.token).toBe(REDACTED);+ expect(args.contact.phone).toBe("555");+ expect(args.contact.firstName).toBe("A");+ });+});diff --git a/packages/logger/src/redaction.ts b/packages/logger/src/redaction.tsnew file mode 100644index 0000000000..a07320fb51--- /dev/null+++ b/packages/logger/src/redaction.ts@@ -0,0 +1,37 @@+import { DEFAULT_REDACT_FIELDS } from "@logtape/redaction";++export const REDACTED = "[REDACTED]";++/**+ * Field-name patterns whose values are masked in logs. LogTape's defaults minus+ * /email/i, /phone/i and /address/i: in an ERP those are ordinary business data+ * (contact.workPhone, address.addressLine1, customer emails), and hiding them+ * turns the log into a lie about what a request contained — a redacted `phone`+ * field once made a PGRST204 failure look impossible because the logged+ * arguments no longer showed the key that caused it.+ */+export const REDACT_FIELD_PATTERNS = DEFAULT_REDACT_FIELDS.filter(+ (pattern) =>+ !(+ pattern instanceof RegExp &&+ ["email", "phone", "address"].includes(pattern.source)+ )+);++/**+ * Replace a matched field's value with a visible marker. LogTape's default+ * action DELETES the field, and a deleted key is indistinguishable from one the+ * caller never sent.+ */+export function maskRedactedField(): unknown {+ return REDACTED;+}++/** Does a field name match any redaction pattern? Shared by the HTTP capture. */+export function isSensitiveKey(key: string): boolean {+ return REDACT_FIELD_PATTERNS.some((pattern) =>+ typeof pattern === "string"+ ? key.toLowerCase().includes(pattern.toLowerCase())+ : pattern.test(key)+ );+}