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.

3.0 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 {
  getCarbonServiceRole,
  getUserScopedClient
} from "@carbon/auth/client.server";
import { verifyDownloadToken } from "@carbon/auth/download-token.server";
import { storage } from "@carbon/files";
import { redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { recordDocumentDownload } from "~/modules/documents/documents.server";
import { shareLinkContext } from "~/modules/service-context.server";
import { path } from "~/utils/path";

// Pure resource route (loader only, no default export): it always returns a
// Response — the file bytes on success, or a redirect to the friendly error page
// on any failure. The token is the credential; the clicker needs no Carbon login.
export async function loader({ params }: LoaderFunctionArgs) {
  const { token } = params;

  const fail = (reason: "invalid" | "unavailable") =>
    redirect(path.to.downloadError(reason));

  if (!token) return fail("invalid");

  let payload;
  try {
    payload = await verifyDownloadToken(token);
  } catch {
    // Forged / corrupt signature or unexpected claim shape.
    return fail("invalid");
  }

  const { userId, companyId, documentId } = payload;

  try {
    // Permission + availability in one shot: read the document AS the encoded
    // user via RLS. No row => the user lacks documents_view / readGroups access,
    // or the document was deleted. companyId is enforced to prevent any
    // cross-tenant access even if document ids were to collide.
    const userClient = await getUserScopedClient(userId);
    const doc = await userClient
      .from("document")
      .select("id, name, path")
      .eq("id", documentId)
      .eq("companyId", companyId)
      .maybeSingle();

    if (doc.error || !doc.data?.path) return fail("unavailable");

    // Access already proven above; fetch the bytes with the service role.
    // Documents live in the company's own bucket, keyed directly by
    // `document.path` (mirrors useDocument.ts).
    const file = await storage(getCarbonServiceRole())
      .company(companyId)
      .download(doc.data.path);

    if (!file.data) return fail("unavailable");

    // Best-effort audit log mirroring useDocument's "Download" transaction, so
    // history stays consistent. A failure never blocks the download.
    const ctx = await shareLinkContext({ companyId, createdBy: userId });
    if (ctx) await recordDocumentDownload(ctx, { documentId });

    const filename = (doc.data.name ?? "download").replace(/["\r\n]/g, "");
    return new Response(file.data, {
      status: 200,
      headers: {
        "Content-Type": "application/octet-stream",
        "Content-Disposition": `attachment; filename="${filename}"; filename*=UTF-8''${encodeURIComponent(
          doc.data.name ?? "download"
        )}`
      }
    });
  } catch {
    return fail("unavailable");
  }
}