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.

8.1 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 { withContext } from "@logtape/logtape";
import { createId } from "@paralleldrive/cuid2";
import {
  createContext,
  type MiddlewareFunction,
  type RouterContextProvider
} from "react-router";
import {
  getRequestContext,
  requestContextMiddleware,
  requestDetailContext
} from "./context.server";
import { isSensitiveKey, REDACTED, redactSearch } from "./redaction";
import { annotateRequestSpan } from "./tracing.server";

// 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
// start, so a new subpath 500s until every running dev server is restarted.
// TODO: once a restart is coordinated, add `"./context.server"` to this
// package's `exports` and repoint the four importers (both apps' root.tsx,
// auth's auth.server.ts and users.server.ts) at it, then drop this re-export.
export {
  currentRequest,
  describeRequest,
  getRequestContext,
  getRouterContext,
  isReadRequest,
  oncePerRead,
  oncePerRequest,
  requestContextMiddleware
} from "./context.server";

import { getLogger } from "./logger";

/**
 * Run `fn` inside a LogTape implicit-context scope so every log line emitted
 * within it carries `properties` — the same mechanism `requestIdMiddleware`
 * uses for `requestId`. Scopes nest and merge, so calling this inside a
 * request adds to the request's context rather than replacing it. Use it to
 * stamp identity that a whole request shares (e.g. `companyId`/`userId` once
 * auth resolves) instead of repeating the fields at every log call site.
 */
export { withContext as withLogContext } from "@logtape/logtape";

export const REQUEST_ID_HEADER = "x-request-id";

/** Only these carry a body worth logging; GET/HEAD/OPTIONS don't. */
const BODY_LOG_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/**
 * Cap on how large a body we'll buffer for logging. Bounds memory: we require a
 * `content-length` at/under this before reading, so a 120MB CAD upload is never
 * pulled into the log path.
 */
const BODY_LOG_MAX_BYTES = 8 * 1024;

/**
 * Recursively mask values whose key matches a sensitive-field pattern (the same
 * `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);
  if (value && typeof value === "object") {
    const out: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(value)) {
      out[k] = isSensitiveKey(k) ? REDACTED : redactBody(v);
    }
    return out;
  }
  return value;
}

/**
 * Best-effort capture of a request body for debug logging. Returns a redacted
 * object for JSON / form-urlencoded bodies, a short marker string for skipped
 * ones (multipart, oversized, unknown length), or `undefined` for methods /
 * content-types we don't log. Never throws — a parse failure yields a marker.
 *
 * Reads a clone so the route handler's body stream stays intact.
 */
async function captureRequestBody(request: Request): Promise<unknown> {
  if (!BODY_LOG_METHODS.has(request.method)) return undefined;

  const contentType = request.headers.get("content-type") ?? "";
  if (contentType.includes("multipart/form-data")) {
    return "<multipart form-data not captured>";
  }

  const isJson = contentType.includes("application/json");
  const isForm = contentType.includes("application/x-www-form-urlencoded");
  if (!isJson && !isForm) return undefined;

  // Require a known, bounded length so we never buffer an unbounded stream.
  const lengthHeader = request.headers.get("content-length");
  if (lengthHeader === null) return "<unknown length not captured>";
  const length = Number(lengthHeader);
  if (!Number.isFinite(length)) return "<unknown length not captured>";
  if (length > BODY_LOG_MAX_BYTES) return `<${length} bytes not captured>`;
  if (length === 0) return undefined;

  try {
    if (isForm) {
      const form = await request.clone().formData();
      const obj: Record<string, unknown> = {};
      for (const [k, v] of form.entries()) {
        obj[k] = typeof v === "string" ? v : "<file>";
      }
      return redactBody(obj);
    }
    const text = await request.clone().text();
    return redactBody(JSON.parse(text));
  } catch {
    return "<unparseable body>";
  }
}

/** Request-scoped correlation id, readable in loaders/actions via `getRequestId`. */
export const requestIdContext = createContext<string | null>(null);

/**
 * The current request's correlation id.
 *
 * Pass `context` explicitly from a loader/action, or omit it to read the
 * ambient request context published by `requestContextMiddleware` — which is
 * what makes this callable from a plain service function.
 */
export function getRequestId(context?: RouterContextProvider): string | null {
  if (context) return context.get(requestIdContext);
  return getRequestContext(requestIdContext) ?? null;
}

const log = getLogger("http");

/**
 * Assigns a cloud-agnostic request id (reuses an inbound `x-request-id`, else
 * generates one), echoes it on the response, and runs the rest of the request
 * inside a LogTape implicit-context scope so every `getLogger(...)` call in
 * loaders/actions/services during this request carries `{ requestId }`.
 *
 * Register FIRST in an app's `middleware` array so downstream middleware and
 * handlers run inside the context scope.
 */
export const requestIdMiddleware: MiddlewareFunction<Response> = async (
  { request, context },
  next
) => {
  const requestId = request.headers.get(REQUEST_ID_HEADER) ?? createId();
  context.set(requestIdContext, requestId);

  const { method } = request;
  const { pathname, search } = new URL(request.url);
  const start = performance.now();

  // Capture the body only when debug is actually enabled — skips the clone +
  // parse entirely at the prod `info` default. Done before `next()` so the
  // clone happens while the stream is untouched.
  const body = log.isEnabledFor("debug")
    ? await captureRequestBody(request)
    : undefined;

  const response = await withContext({ requestId }, async () => {
    const res = await next();
    annotateRequestSpan({
      "http.response.status_code": res.status,
      "carbon.request_id": requestId,
      // The client left before the response was ready, so a read's queries
      // were cancelled and its status says nothing about the server.
      ...(request.signal.aborted && { "carbon.request.abandoned": true })
    });
    // Debug-level so it is visible in dev but filtered by the prod `info`
    // default — the pipeline is observable with zero migrated call sites.
    // Rendered as a Morgan "dev"-style colored line in dev (see
    // http-formatter.ts) and as a structured JSONL record in prod. When a
    // request body was captured, it rides on the same record (`body`).
    const detail = context.get(requestDetailContext);
    log.debug(
      detail
        ? "{method} {pathname} {detail} → {status} in {responseTime}ms"
        : "{method} {pathname} → {status} in {responseTime}ms",
      {
        method,
        pathname,
        ...(detail ? { detail } : {}),
        search: redactSearch(search),
        status: res.status,
        responseTime: performance.now() - start,
        ...(body === undefined ? {} : { body })
      }
    );
    return res;
  });

  response.headers.set(REQUEST_ID_HEADER, requestId);
  return response;
};

/**
 * The request scope in one middleware: publishes the request context
 * (`requestContextMiddleware`) and, inside it, assigns the request id and
 * writes the access log (`requestIdMiddleware`). Register FIRST in an app's
 * root `middleware`, so everything downstream runs inside both.
 */
export const requestMiddleware: MiddlewareFunction<Response> = (args, next) =>
  requestContextMiddleware(args, () =>
    Promise.resolve(requestIdMiddleware(args, next) as Response)
  );