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.

14.4 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 type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
import { oncePerRead } from "@carbon/logger/middleware.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getCarbonServiceRole } from "../lib/supabase/client.server";
import type { Permission, Result } from "../types";
import { error, success } from "../utils/result";
import { logRoleChange } from "./auth-events.server";
import {
  getClaims,
  getPermissionCacheKey,
  makePermissionsFromClaims
} from "./users";

const log = getLogger("auth");

// TTL for the cached permission claims. Bounds staleness if an invalidation
// (company switch / deactivation) fails to delete the key — the cache heals
// itself on expiry. 1 hour, matching the auth package's other short-lived keys.
const PERMISSION_CACHE_TTL_SECONDS = 3600;

export async function getUserByEmail(email: string) {
  return getCarbonServiceRole()
    .from("user")
    .select("*")
    .eq("email", email.toLowerCase())
    .single();
}

/**
 * Claims for a user in a company, resolved once per read request.
 *
 * Every matched loader that calls `requirePermissions` — plus the app-shell
 * loaders that call this directly — otherwise repeated the same Redis GET.
 *
 * Read-gated deliberately: React Router runs an action and its loader
 * revalidation in one request, so memoizing here on a mutating request could
 * let a permission gate pass on claims the action had just revoked.
 */
export function getUserClaims(userId: string, companyId: string) {
  return oncePerRead(`claims:${userId}:${companyId}`, () =>
    loadUserClaims(userId, companyId)
  );
}

async function loadUserClaims(userId: string, companyId: string) {
  let claims: {
    permissions: Record<string, Permission>;
    role: string | null;
  } | null = null;

  try {
    const cachedClaims = await redis.get(getPermissionCacheKey(userId));
    if (cachedClaims) {
      claims = JSON.parse(cachedClaims) as {
        permissions: Record<string, Permission>;
        role: string | null;
      };
    }
  } catch (e) {
    log.error("Failed to get claims from redis", { error: e });
  } finally {
    // if we don't have permissions from redis, get them from the database
    if (!claims) {
      // TODO: remove service role from here, and move it up a level
      const rawClaims = await getClaims(
        getCarbonServiceRole(),
        userId,
        companyId
      );
      if (rawClaims.error || rawClaims.data === null) {
        log.error("Failed to get claims", { rawClaims });
        throw new Error("Failed to get claims");
      }

      // convert rawClaims to permissions
      claims = makePermissionsFromClaims(rawClaims.data as Json[]);

      // store claims in redis — best-effort. A null/failed write (Redis down,
      // fail-soft via @carbon/kv withResilience) must not abort the in-flight
      // request; we already have the claims from the DB.
      try {
        await redis.set(
          getPermissionCacheKey(userId),
          JSON.stringify(claims),
          "EX",
          PERMISSION_CACHE_TTL_SECONDS
        );
      } catch (e) {
        log.error("Failed to cache claims in redis", { error: e });
      }

      if (!claims) {
        throw new Error("Failed to get claims");
      }
    }

    return claims;
  }
}

export async function deactivateCustomer(
  serviceRole: SupabaseClient<Database>,
  userId: string,
  companyId: string,
  actorId?: string,
  ip?: string
): Promise<Result> {
  const currentPermissions = await serviceRole
    .from("userPermission")
    .select("*")
    .eq("id", userId)
    .maybeSingle();

  if (currentPermissions.error) {
    return error(currentPermissions.error, "Failed to get user permissions");
  }

  const before = (currentPermissions.data?.permissions ?? {}) as Record<
    string,
    string[]
  >;
  const permissions = Object.entries(before).reduce<Record<string, string[]>>(
    (acc, [key, value]) => {
      acc[key] = value.filter((id) => id !== companyId);
      return acc;
    },
    {}
  );

  const companyGroups = await serviceRole
    .from("group")
    .select("id")
    .eq("companyId", companyId);

  const groupIds = companyGroups.data?.map((g) => g.id) ?? [];

  const [updatePermissions, userToCompanyDelete, customerAccountDelete] =
    await Promise.all([
      serviceRole
        .from("userPermission")
        .update({ permissions })
        .eq("id", userId),
      serviceRole
        .from("userToCompany")
        .delete()
        .eq("userId", userId)
        .eq("companyId", companyId),
      serviceRole
        .from("customerAccount")
        .delete()
        .eq("id", userId)
        .eq("companyId", companyId),
      ...(groupIds.length > 0
        ? [
            serviceRole
              .from("membership")
              .delete()
              .eq("memberUserId", userId)
              .in("groupId", groupIds)
          ]
        : [])
    ]);

  if (updatePermissions.error) {
    return error(updatePermissions.error, "Failed to update user permissions");
  }

  if (userToCompanyDelete.error) {
    return error(
      userToCompanyDelete.error,
      "Failed to remove user from company"
    );
  }

  if (customerAccountDelete.error) {
    return error(
      customerAccountDelete.error,
      "Failed to remove customer account"
    );
  }

  logRoleChange({
    actor: actorId,
    targetUserId: userId,
    companyId,
    beforeRole: "customer",
    afterRole: null,
    before,
    after: permissions,
    ip,
    reason: "deactivate"
  });

  // Same ownership as the employee path below: invalidate here so the
  // create*Account rollbacks, which call this directly, cannot leave revoked
  // grants readable from cache.
  await redis.del(getPermissionCacheKey(userId));

  return success("Sucessfully deactivated customer");
}

export async function deactivateEmployee(
  serviceRole: SupabaseClient<Database>,
  userId: string,
  companyId: string,
  actorId?: string,
  ip?: string
): Promise<Result> {
  const currentPermissions = await serviceRole
    .from("userPermission")
    .select("*")
    .eq("id", userId)
    .maybeSingle();

  if (currentPermissions.error) {
    return error(currentPermissions.error, "Failed to get user permissions");
  }

  const before = (currentPermissions.data?.permissions ?? {}) as Record<
    string,
    string[]
  >;
  const permissions = Object.entries(before).reduce<Record<string, string[]>>(
    (acc, [key, value]) => {
      acc[key] = value.filter((id) => id !== companyId);
      return acc;
    },
    {}
  );

  const companyGroups = await serviceRole
    .from("group")
    .select("id")
    .eq("companyId", companyId);

  const groupIds = companyGroups.data?.map((g) => g.id) ?? [];

  const [updatePermissions, userToCompanyDelete, employeeDeactivate] =
    await Promise.all([
      serviceRole
        .from("userPermission")
        .update({ permissions })
        .eq("id", userId),
      serviceRole
        .from("userToCompany")
        .delete()
        .eq("userId", userId)
        .eq("companyId", companyId),
      serviceRole
        .from("employee")
        .update({ active: false })
        .eq("id", userId)
        .eq("companyId", companyId),
      // "employeeJob" is deliberately left in place. It carries org placement —
      // title, start date, department, shift, manager, location, tags, custom
      // fields — none of which grants access; membership ("userToCompany"),
      // permissions, and "employee".active are what gate it, and all three are
      // cleared here. Deleting the row made deactivation lossy: nothing in the
      // re-invite path can reconstruct it, so a revoked employee who was later
      // re-invited came back with their placement silently blanked.
      ...(groupIds.length > 0
        ? [
            serviceRole
              .from("membership")
              .delete()
              .eq("memberUserId", userId)
              .in("groupId", groupIds)
          ]
        : [])
    ]);

  if (updatePermissions.error) {
    return error(updatePermissions.error, "Failed to update user permissions");
  }

  if (userToCompanyDelete.error) {
    return error(
      userToCompanyDelete.error,
      "Failed to remove user from company"
    );
  }

  if (employeeDeactivate.error) {
    return error(employeeDeactivate.error, "Failed to deactivate employee");
  }

  logRoleChange({
    actor: actorId,
    targetUserId: userId,
    companyId,
    beforeRole: "employee",
    afterRole: null,
    before,
    after: permissions,
    ip,
    reason: "deactivate"
  });

  // The permissions this function just revoked are cached in Redis, and
  // `requirePermissions` reads that cache before the database. Invalidating
  // here rather than only in `deactivateUser` covers the callers that reach
  // this function directly — the create*Account rollback paths — which
  // otherwise left a deactivated user's grants live until the 1h TTL.
  await redis.del(getPermissionCacheKey(userId));

  return success("Sucessfully deactivated employee");
}

export async function deactivateUser(
  serviceRole: SupabaseClient<Database>,
  userId: string,
  companyId: string,
  actorId?: string,
  ip?: string
) {
  const userToCompany = await serviceRole
    .from("userToCompany")
    .select("role")
    .eq("userId", userId)
    .eq("companyId", companyId)
    .single();

  let result: Result;

  if (userToCompany.error) {
    // No userToCompany row — either pending invite, or already deactivated.
    const user = await serviceRole
      .from("user")
      .select("*")
      .eq("id", userId)
      .single();
    if (user.error) {
      return error(user.error, "Failed to get user");
    }

    const invite = await serviceRole
      .from("invite")
      .select("*")
      .eq("email", user.data?.email)
      .eq("companyId", companyId)
      .maybeSingle();

    if (!invite.data) {
      // No userToCompany and no invite — already fully deactivated.
      return success("User already deactivated");
    }

    if (invite.data.role === "customer") {
      result = await deactivateCustomer(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else if (invite.data.role === "employee") {
      result = await deactivateEmployee(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else if (invite.data.role === "supplier") {
      result = await deactivateSupplier(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else {
      throw new Error("Invalid user role");
    }
  } else {
    if (userToCompany.data?.role === "customer") {
      result = await deactivateCustomer(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else if (userToCompany.data?.role === "employee") {
      result = await deactivateEmployee(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else if (userToCompany.data?.role === "supplier") {
      result = await deactivateSupplier(
        serviceRole,
        userId,
        companyId,
        actorId,
        ip
      );
    } else {
      throw new Error("Invalid user role");
    }
  }

  // Clear stale permission cache
  if (result && result.success) {
    await redis.del(getPermissionCacheKey(userId));
  }

  // Mark any invite for this user/company as revoked so the link cannot be
  // redeemed and the UI no longer surfaces resend/revoke actions on it.
  if (result && result.success) {
    const userRecord = await serviceRole
      .from("user")
      .select("email")
      .eq("id", userId)
      .single();
    if (!userRecord.error && userRecord.data?.email) {
      await serviceRole
        .from("invite")
        .update({ revokedAt: new Date().toISOString() })
        .eq("email", userRecord.data.email)
        .eq("companyId", companyId)
        .is("revokedAt", null);
    }
  }

  return result;
}

export async function deactivateSupplier(
  serviceRole: SupabaseClient<Database>,
  userId: string,
  companyId: string,
  actorId?: string,
  ip?: string
): Promise<Result> {
  const currentPermissions = await serviceRole
    .from("userPermission")
    .select("*")
    .eq("id", userId)
    .maybeSingle();

  if (currentPermissions.error) {
    return error(currentPermissions.error, "Failed to get user permissions");
  }

  const before = (currentPermissions.data?.permissions ?? {}) as Record<
    string,
    string[]
  >;
  const permissions = Object.entries(before).reduce<Record<string, string[]>>(
    (acc, [key, value]) => {
      acc[key] = value.filter((id) => id !== companyId);
      return acc;
    },
    {}
  );

  const companyGroups = await serviceRole
    .from("group")
    .select("id")
    .eq("companyId", companyId);

  const groupIds = companyGroups.data?.map((g) => g.id) ?? [];

  const [updatePermissions, userToCompanyDelete, supplierAccountDelete] =
    await Promise.all([
      serviceRole
        .from("userPermission")
        .update({ permissions })
        .eq("id", userId),
      serviceRole
        .from("userToCompany")
        .delete()
        .eq("userId", userId)
        .eq("companyId", companyId),
      serviceRole
        .from("supplierAccount")
        .delete()
        .eq("id", userId)
        .eq("companyId", companyId),
      ...(groupIds.length > 0
        ? [
            serviceRole
              .from("membership")
              .delete()
              .eq("memberUserId", userId)
              .in("groupId", groupIds)
          ]
        : [])
    ]);

  if (updatePermissions.error) {
    return error(updatePermissions.error, "Failed to update user permissions");
  }

  if (userToCompanyDelete.error) {
    return error(
      userToCompanyDelete.error,
      "Failed to remove user from company"
    );
  }

  if (supplierAccountDelete.error) {
    return error(
      supplierAccountDelete.error,
      "Failed to remove supplier account"
    );
  }

  logRoleChange({
    actor: actorId,
    targetUserId: userId,
    companyId,
    beforeRole: "supplier",
    afterRole: null,
    before,
    after: permissions,
    ip,
    reason: "deactivate"
  });

  // See deactivateEmployee: the direct callers own nothing, this function does.
  await redis.del(getPermissionCacheKey(userId));

  return success("Sucessfully deactivated supplier");
}