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.

25.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 {
  CarbonEdition,
  CarbonProvider,
  CONTROLLED_ENVIRONMENT,
  getCarbon,
  getMESUrl,
  ITAR_RIDER_PDF_PATH,
  isAuthProviderEnabled,
  SESSION_HEARTBEAT_MS,
  SESSION_IDLE_LOCK_MS
} from "@carbon/auth";
import { getCompanyId, setCompanyId } from "@carbon/auth/company.server";
import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
import {
  destroyAuthSession,
  requireAuthSession,
  updateCompanySession
} from "@carbon/auth/session.server";
import { getUserClaims } from "@carbon/auth/users.server";
import { withEmailDelivery } from "@carbon/ee";
import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { isAuditLogEnabled } from "@carbon/ee/audit.server";
import { getPlan } from "@carbon/ee/plan.server";
import { evaluateBrowserFlags } from "@carbon/env/flags.server";
import { getVapidDetails } from "@carbon/env/push.server";
import { SERVER_MAIL_CONFIGURED } from "@carbon/lib/email.server";
import { getLogger } from "@carbon/logger";
import { getImplementationCheckStates } from "@carbon/onboarding/server";
import type { PrintingSettings } from "@carbon/printing";
import { PrintingProvider } from "@carbon/printing/ui";
import { RouteRealtime, useLoaderQuery } from "@carbon/query";
import { setClientCompanyId } from "@carbon/query/cache";
import {
  AnnouncementBar,
  ItarEntityCertification,
  ItarEntityPendingBlock,
  ItarUserCertification,
  SidebarProvider,
  TooltipProvider,
  useKeyboardWedge,
  useNProgress,
  useViewport
} from "@carbon/react";
import { HalloweenLayer } from "@carbon/react/Halloween";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
import {
  Edition,
  formatDate,
  redirect,
  redirectExternal,
  requiresItarEntityCertification,
  SHELL_MAX_AGE_MS
} from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import posthog from "posthog-js";
import type { ReactNode } from "react";
import { Suspense, useEffect } from "react";
import type {
  LoaderFunctionArgs,
  ShouldRevalidateFunction
} from "react-router";
import { Await, data, Outlet, useLoaderData } from "react-router";
import { RealtimeDataProvider } from "~/components";
import ChangelogPanel from "~/components/ChangelogPanel";
import {
  ModuleSidebarLayout,
  PrimaryNavigation,
  Topbar
} from "~/components/Layout";
import {
  MobileAppBar,
  MobileBottomChrome,
  MobileDock
} from "~/components/Layout/Mobile";
import MfaEnrollmentRequired from "~/components/MfaEnrollmentRequired";
import SessionLockOverlay from "~/components/SessionLockOverlay";
import ShortcutHelp from "~/components/ShortcutHelp";
import { TimeCardWarning } from "~/components/TimeCardWarning";
import TrainingPanel from "~/components/TrainingPanel";
import { useIdle, usePermissions, useRecordRecentlyViewed } from "~/hooks";
import { useChangelogPanel } from "~/hooks/useChangelogPanel";
import { useTrainingPanel } from "~/hooks/useTrainingPanel";
import { AgentRoot } from "~/modules/agent/ui/AgentRoot";
import { getOpenClockEntry } from "~/modules/people/people.service";
import {
  employeeCompaniesOf,
  getEmployeeCompanies
} from "~/modules/settings/settings.service";
import {
  getAppShell,
  getCustomFieldsSchemas,
  getImplementationSignals
} from "~/modules/shared/shared.service";
import AccountSettings from "~/modules/users/ui/AccountSettings";
import {
  getCachedChangelogPanelEntry,
  getItarCertificationStatus
} from "~/modules/users/users.service";
import type { loader as systemStatusLoader } from "~/routes/api+/system-status";
import { ERP_URL, MES_URL, path } from "~/utils/path";

const log = getLogger("erp", "auth");

// Set from the component when loader data arrives, not in shouldRevalidate:
// link prefetching calls that too.
let shellLoadedAt = Date.now();

export const shouldRevalidate: ShouldRevalidateFunction = ({
  currentUrl,
  formMethod,
  formAction,
  defaultShouldRevalidate
}) => {
  // The refreshed session reaches the client through this loader.
  if (formAction === path.to.refreshSession) return true;

  if (
    currentUrl.pathname.startsWith("/x/settings") ||
    currentUrl.pathname.startsWith("/x/users") ||
    currentUrl.pathname.startsWith("/refresh-session") ||
    currentUrl.pathname.startsWith("/x/acknowledge") ||
    currentUrl.pathname.startsWith("/x/get-started") ||
    currentUrl.pathname.startsWith("/x/shared/views")
  ) {
    return true;
  }

  // Only a mutation can change what the shell returns, so a GET re-runs it
  // only once the data has aged out — that covers out-of-band changes.
  if (!formMethod || formMethod === "GET") {
    return Date.now() - shellLoadedAt > SHELL_MAX_AGE_MS;
  }

  return defaultShouldRevalidate;
};

export async function loader({ request }: LoaderFunctionArgs) {
  const authSession = await requireAuthSession(request, { verify: true });
  const { accessToken, companyId, email, expiresAt, expiresIn, userId } =
    authSession;

  // Block ERP access when console mode is active on this terminal.
  // Console terminals should only access the MES app.
  if (authSession.console) {
    throw redirectExternal(getMESUrl());
  }

  // const { computeRegion, proxyRegion } = parseVercelId(
  //   request.headers.get("x-vercel-id")
  // );

  // console.log({
  //   computeRegion,
  //   proxyRegion,
  // });

  const client = getCarbon(accessToken);

  // The user's and the company's rows, in one round trip. Started here so the
  // hub's signal probes can chain off it and overlap the fan-out below.
  const shellPromise = getAppShell(client, companyId, userId);

  // Only probe product signals when the company is actually enrolled, so the
  // home card + nav badge count gates the same way the hub page does.
  const implementationSignalsPromise = shellPromise.then(({ data }) => {
    const hub = data?.implementationHub;
    // A finished hub shows no badge and no card, so it needs no signals.
    return hub && hub.status !== "complete" && hub.status !== "archived"
      ? getImplementationSignals(client, companyId)
      : null;
  });

  // ITAR gate status — only queried in controlled environments; elsewhere the
  // gate never renders, so default to "certified" and skip the round-trip.
  // `entityRequired` is layered on below, once the user's email is known.
  const itarCertificationPromise = CONTROLLED_ENVIRONMENT
    ? getItarCertificationStatus(client, companyId, userId)
    : Promise.resolve({ entityCertified: true, userCertified: true });

  // The hub row (in the shell read, awaited below) decides whether the primary
  // nav has a Get Started item and the home page a card: streamed, both arrived
  // after first paint and pushed the page down. Progress only fills in the
  // badge count and the card's bar, in place, so it stays streamed. It catches:
  // the loader can exit early with nothing awaiting it.
  const implementationProgress = Promise.all([
    getImplementationCheckStates(client, companyId),
    implementationSignalsPromise
  ])
    .then(([checkStates, signals]) => ({
      checkStates: checkStates.data ?? [],
      signals
    }))
    .catch((error) => {
      log.error("Failed to load implementation progress", {
        companyId,
        error
      });
      return { checkStates: [], signals: null };
    });
  const auditLogEnabled = isAuditLogEnabled(client, companyId).catch(
    () => false
  );
  // Streamed, not awaited; each catches for the same early-exit reason.
  // Whether this user dismissed it is a user flag, read client-side.
  const changelog = getCachedChangelogPanelEntry().catch(() => null);

  // Parallelize all requests
  const [shell, stripeCustomer, plan, customFields, claims, itarCertification] =
    await Promise.all([
      shellPromise,
      getStripeCustomerByCompanyId(companyId, userId),
      getPlan(client, companyId),
      getCustomFieldsSchemas(client, { companyId }),
      getUserClaims(userId, companyId),
      itarCertificationPromise
    ]);

  // The same shapes the nine separate reads returned, so what follows reads as
  // it did. A failed shell read fails each of them, as each could before.
  const read = <T,>(value: T | undefined) => ({
    data: value ?? null,
    error: shell.error
  });
  const companies = read(shell.data?.companies);
  const integrations = read(shell.data?.companyIntegrations);
  // Whether documents can be emailed, settled once for every
  // `integrations.has("email")` (withEmailDelivery).
  const companyIntegrations = withEmailDelivery(
    integrations.data ?? [],
    companyId,
    SERVER_MAIL_CONFIGURED
  );
  const companySettings = read(shell.data?.companySettings ?? undefined);
  const savedViews = read(shell.data?.savedViews);
  const user = read(shell.data?.user ?? undefined);
  const groups = { data: shell.data?.groups ?? [], error: shell.error };
  const defaults = read(shell.data?.defaults ?? undefined);
  const modulePreferences = read(shell.data?.modulePreferences);
  const printerRoutes = read(shell.data?.printerRoutes);

  // Empty groups is a valid pre-onboarding state (a first-run user with no
  // company yet has zero memberships → groups is []), NOT an auth failure —
  // logging out here made the `requiresOnboarding` redirect below unreachable.
  // Only a genuine RPC error (groups.error) logs out.
  if (!claims || user.error || !user.data || groups.error) {
    // Four very different faults share this exit: no claims usually means the
    // user has no company membership (get_claims returned nothing), while the
    // user/groups errors mean a failed RPC. Record which one before bouncing.
    const reason = !claims
      ? "no-claims"
      : user.error
        ? "user-error"
        : !user.data
          ? "no-user-row"
          : "groups-error";

    log.warn("Destroying auth session in x+/_layout loader", {
      userId,
      companyId,
      reason,
      noClaims: !claims,
      userError: user.error?.message ?? null,
      hasUserData: Boolean(user.data),
      groupsError: groups.error?.message ?? null
    });

    throw await destroyAuthSession(request, reason);
  }

  // Derived from the read above. A failed read falls back to its own query, so
  // a multi-company user still reaches the picker rather than onboarding.
  const employeeCompanies = companies.data
    ? employeeCompaniesOf(companies.data)
    : ((await getEmployeeCompanies(client, userId)).data ?? []);
  const hasMultipleCompanies = employeeCompanies.length > 1;

  // Send multi-company users to the picker, preserving where they were headed.
  const redirectToPicker = () => {
    const url = new URL(request.url);
    const dest = `${url.pathname}${url.search}`;
    return redirect(
      `${path.to.selectCompany}?redirectTo=${encodeURIComponent(dest)}`
    );
  };

  // Multi-company users must actively choose a company. The companyId cookie is
  // the "has chosen this session" marker — set only by the picker / company
  // switch and cleared on logout. Until it's present, force the picker so we
  // never silently serve the alphabetically-first company.
  if (hasMultipleCompanies && !getCompanyId(request)) {
    throw redirectToPicker();
  }

  let company = companies.data?.find((c) => c.companyId === companyId);

  if (!company && companies.data?.length) {
    // Session company is no longer valid (e.g. access revoked). Multi-company
    // users re-pick; single-company users auto-enter their only company.
    if (hasMultipleCompanies) {
      throw redirectToPicker();
    }
    company = employeeCompanies[0] ?? companies.data[0];
    const sessionCookie = await updateCompanySession(
      request,
      company.id!,
      company.companyGroupId ?? ""
    );
    const companyIdCookie = setCompanyId(company.id!);
    throw redirect(path.to.authenticatedRoot, {
      headers: [
        ["Set-Cookie", sessionCookie],
        ["Set-Cookie", companyIdCookie]
      ]
    });
  }

  const requiresOnboarding =
    !company?.name || (CarbonEdition === Edition.Cloud && !stripeCustomer);
  if (requiresOnboarding) {
    throw redirect(path.to.onboarding.root);
  }

  // Org-enforced MFA. A controlled deployment forces it regardless of the
  // company toggle (NIST 800-171 3.5.3 requires MFA for network access to
  // non-privileged accounts), so a company cannot switch it back off.
  const mfaRequired =
    CONTROLLED_ENVIRONMENT || companySettings.data?.requireMfa === true;
  // SSO sessions trust the IdP for MFA in all environments, including
  // controlled — user decision: attestation is delegated to the IdP policy.
  const ssoMfaExempt = Boolean(authSession.ssoProviderId);
  // Redis-cached + memoized per read; only queried when it could gate.
  const mfaEnrolled =
    mfaRequired && !ssoMfaExempt
      ? await userHasVerifiedTotpFactor(userId)
      : true;

  return data({
    session: {
      accessToken,
      expiresIn,
      expiresAt
    },
    auditLogEnabled,
    company,
    companies: companies.data ?? [],
    // Feature flags with `browser: true`, read with `useFeatureFlags().feature(key)`.
    flags: await evaluateBrowserFlags({ companyId, email }),
    companySettings: companySettings.data ?? null,
    customFields: customFields.data ?? [],
    defaults: defaults.data,
    integrations: companyIntegrations,
    groups: groups.data ?? [],
    permissions: claims?.permissions,
    plan,
    // Null hides the bell's "Enable browser notifications" row: the
    // deployment has no push keys (no SESSION_SECRET).
    pushPublicKey: getVapidDetails()?.publicKey ?? null,
    role: claims?.role,
    user: user.data,
    modulePreferences: modulePreferences.data ?? [],
    savedViews: savedViews.data ?? [],
    printerRoutes: printerRoutes.data ?? [],
    implementationHub: shell.data?.implementationHub ?? null,
    implementationProgress,
    changelog,
    itarCertification: {
      ...itarCertification,
      // Server-decided, never client-inferred: the gate must not be skippable
      // by anything the browser can set.
      entityRequired: requiresItarEntityCertification(user.data.email)
    },
    mfaEnrollment: {
      // Server-decided, never client-inferred — same reason as the ITAR gate.
      required: mfaRequired && !mfaEnrolled,
      controlledEnvironment: CONTROLLED_ENVIRONMENT
    },
    // Session lock/termination (NIST 3.1.10/3.1.11) — client idle UX config. The
    // ERP shell already redirected any console session to MES above, so no console
    // exemption is needed here. Server enforcement lives in requireAuthSession.
    sessionTimeout: {
      enabled: CONTROLLED_ENVIRONMENT,
      idleMs: SESSION_IDLE_LOCK_MS,
      heartbeatMs: SESSION_HEARTBEAT_MS,
      // Offer passkey re-auth on the lock overlay when the provider is enabled;
      // the /unlock action gates the actual credential, TOTP stays available.
      hasPasskeyAuth: isAuthProviderEnabled("passkey")
    },
    supplierApprovalRequired: isApprovalRequired(client, "supplier", companyId),
    openClockEntry: companySettings.data?.timeCardEnabled
      ? getOpenClockEntry(client, userId, companyId)
      : null
  });
}

export default function AuthenticatedRoute() {
  const loaderData = useLoaderData<typeof loader>();
  const { isPhone } = useViewport();
  const {
    company,
    session,
    user,
    companySettings,
    openClockEntry,
    printerRoutes,
    itarCertification,
    mfaEnrollment,
    sessionTimeout
  } = loaderData;
  // During render, not in an effect: clientLoaders and the first child read it.
  setClientCompanyId(company?.id ?? null, user?.id ?? null);
  const { t } = useLingui();
  const systemStatus = useLoaderQuery<typeof systemStatusLoader>(
    path.to.api.systemStatus
  );
  const { locale } = useLocale();
  const moveDate = systemStatus.data?.accountMoveDate;
  // The account move outranks the deployment-wide announcement, and cannot
  // be dismissed: it stays until the date is cleared on the company.
  const announcement = moveDate
    ? {
        id: `account-move:${moveDate}`,
        severity: "warning" as const,
        message: t`🚨 Heads up: on ${formatDate(moveDate, { dateStyle: "long" }, locale)} your account will be moved to erp.try.carbon.ms`,
        dismissible: false
      }
    : systemStatus.data?.announcement;
  // biome-ignore lint/correctness/useExhaustiveDependencies: runs each time the loader does
  useEffect(() => {
    shellLoadedAt = Date.now();
  }, [loaderData]);
  const permissions = usePermissions();
  const { isOpen, training, dismiss } = useTrainingPanel();
  const changelogPanel = useChangelogPanel();

  // Session lock (NIST 3.1.10) — client idle UX only; the server enforces in
  // requireAuthSession. Inert unless CONTROLLED_ENVIRONMENT.
  const { isIdle, resume } = useIdle({
    enabled: sessionTimeout.enabled,
    idleMs: sessionTimeout.idleMs,
    heartbeatMs: sessionTimeout.heartbeatMs,
    heartbeatUrl: "/api/session/heartbeat"
  });

  useNProgress();
  useKeyboardWedge({
    test: (input) => input.startsWith(MES_URL) || input.startsWith(ERP_URL)
  });

  const userId = user?.id;
  const userEmail = user?.email;
  const userFullName = user ? `${user.firstName} ${user.lastName}` : undefined;
  const companyId = company?.companyId;
  const companyName = company?.name;

  // Record every detail document the user opens, for the home page's
  // "Recently viewed" list. Reads the record's title from its breadcrumb handle,
  // so no per-route wiring is needed.
  useRecordRecentlyViewed(companyId);

  // Keyed on the identity rather than run once on mount: switching company
  // redirects back into x+/_layout without unmounting it, so a mount-only
  // effect would leave the previous company attached to every later event.
  // The deps are primitives because `user`/`company` get fresh object
  // identities on every revalidation, and group() re-sends $groupidentify
  // each time it is called.
  useEffect(() => {
    if (!userId) return;

    posthog.identify(userId, { email: userEmail, name: userFullName });

    if (!companyId) return;

    // Adoption is measured per customer, and a user can belong to more than one
    // company — so the company rides on the events rather than on the person.
    // register() puts companyId on every event including autocapture; group()
    // is what lets PostHog aggregate by customer.
    posthog.register({ companyId });
    posthog.group("company", companyId, { name: companyName });
  }, [userId, userEmail, userFullName, companyId, companyName]);

  // ITAR gate: entity Rider acceptance first (only an admin who can bind the
  // company may accept it; everyone else waits), then the user's own U.S.-Person
  // attestation. Declining either logs the user out.
  //
  // `entityRequired` is false for Carbon staff — they provision customer tenants
  // and so hold users_update there, but the Rider binds the customer's own
  // organization and is not theirs to sign. They fall straight through to their
  // own attestation; the customer's first admin binds the customer.
  let itarScreen: ReactNode = null;
  const entityBlocking =
    itarCertification.entityRequired && !itarCertification.entityCertified;
  if (
    CONTROLLED_ENVIRONMENT &&
    (entityBlocking || !itarCertification.userCertified)
  ) {
    if (entityBlocking) {
      itarScreen = permissions.can("update", "users") ? (
        <ItarEntityCertification
          companyName={companyName ?? "your company"}
          riderPdfPath={ITAR_RIDER_PDF_PATH}
          acknowledgeAction={path.to.acknowledge}
          logoutAction={path.to.logout}
        />
      ) : (
        <ItarEntityPendingBlock logoutAction={path.to.logout} />
      );
    } else {
      itarScreen = (
        <ItarUserCertification
          riderPdfPath={ITAR_RIDER_PDF_PATH}
          acknowledgeAction={path.to.acknowledge}
          logoutAction={path.to.logout}
        />
      );
    }
  }

  // Enforced-MFA gate. Rendered in place of the shell rather than redirected
  // to, so the enrollment API routes it calls are never themselves gated.
  // Ordered after ITAR: the export-control attestation is the legal gate and
  // must be answered first.
  const mfaScreen: ReactNode = mfaEnrollment.required ? (
    <MfaEnrollmentRequired
      enrollAction={path.to.mfaEnroll}
      verifyAction={path.to.mfaVerify}
      logoutAction={path.to.logout}
      controlledEnvironment={mfaEnrollment.controlledEnvironment}
      userName={`${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()}
      avatarUrl={user.avatarUrl}
    />
  ) : null;

  return (
    <div className="h-[100dvh] flex flex-col">
      {/* Idle lock conceals the app (3.1.10). Not shown over the ITAR/MFA gates —
          the user has not fully entered the app there. */}
      {isIdle && !itarScreen && !mfaScreen && (
        <SessionLockOverlay
          onUnlocked={resume}
          hasPasskeyAuth={sessionTimeout.hasPasskeyAuth}
        />
      )}
      {(itarScreen ?? mfaScreen) ? (
        (itarScreen ?? mfaScreen)
      ) : (
        <CarbonProvider session={session}>
          <PrintingProvider
            value={{
              printing:
                (companySettings?.printing as PrintingSettings | null) ?? null,
              printerRoutes,
              useMetric: Boolean(companySettings?.useMetric),
              printPath: path.to.manualPrint,
              settingsPath: path.to.printingSettings
            }}
          >
            <RealtimeDataProvider>
              {company?.id && <RouteRealtime companyId={company.id} />}
              <TooltipProvider>
                <SidebarProvider
                  defaultOpen={false}
                  className="h-screen min-h-0"
                >
                  <PrimaryNavigation />
                  <div className="flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border shadow-md relative z-10">
                    {/* Phones: app bar on top; below <main>, a page's
                        bottom bar in flow or the dock floating over it.
                        Mounted only on phones so their hooks
                        (notifications, sheets) never run on desktop. */}
                    {isPhone && <MobileAppBar />}
                    <Topbar />
                    <AnnouncementBar
                      announcement={announcement}
                      userId={user?.id ?? ""}
                      dismissLabel={t`Dismiss`}
                      defaultLinkLabel={t`Learn more`}
                    />
                    <main className="flex-1 overflow-y-auto scrollbar-hide relative">
                      <ModuleSidebarLayout>
                        {/* A company switch stays on the same page. Without the key the page
                            keeps its state, so a form still held the previous company's
                            values and saving wrote them to the new one. */}
                        <Outlet key={companyId} />
                      </ModuleSidebarLayout>
                      {/* Room to scroll a page's end out from under the
                          floating dock. A spacer, not padding: padding would
                          shrink h-full pages and end them above the dock. */}
                      {isPhone && (
                        <div
                          aria-hidden
                          className="h-[var(--dock-height,0px)] md:hidden"
                        />
                      )}
                    </main>
                    {/* Seasonal: shows only with the Halloween theme. Remove
                        with packages/react/src/Halloween/. */}
                    <HalloweenLayer />
                    {isPhone && (
                      <MobileBottomChrome>
                        <MobileDock />
                      </MobileBottomChrome>
                    )}
                  </div>
                </SidebarProvider>
                <TrainingPanel
                  training={training}
                  isOpen={isOpen}
                  onDismiss={dismiss}
                />
                {/* Shares the training panel's corner; training wins while open. */}
                <ChangelogPanel
                  entry={changelogPanel.entry}
                  isOpen={changelogPanel.isOpen && !isOpen}
                  onDismiss={changelogPanel.dismiss}
                />
                <AgentRoot />
                <ShortcutHelp />
                <AccountSettings />
                {companySettings?.timeCardEnabled && (
                  <Suspense fallback={null}>
                    <Await resolve={openClockEntry}>
                      {(resolved) => (
                        <TimeCardWarning
                          openClockEntry={
                            resolved?.data
                              ? {
                                  id: resolved.data.id,
                                  clockIn: resolved.data.clockIn
                                }
                              : null
                          }
                        />
                      )}
                    </Await>
                  </Suspense>
                )}
              </TooltipProvider>
            </RealtimeDataProvider>
          </PrintingProvider>
        </CarbonProvider>
      )}
    </div>
  );
}