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: an invitee who signs in from the sign-in page joins their company (#2025)
Sidcf27fad90221
diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex 259ef5a852..da818b2ed4 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -7,6 +7,7 @@ import type {ServiceContext} from "@carbon/api/service-fn.server";import {+ CarbonEdition,CONTROLLED_ENVIRONMENT,hasPermission,ITAR_RIDER_SHA256,@@ -46,7 +47,8 @@ import {type NotificationTopic,notificationPreferenceCompanyId} from "@carbon/notifications";-import { datetime, getClientIp } from "@carbon/utils";+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";+import { datetime, Edition, getClientIp } from "@carbon/utils";import { now, parseAbsolute } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";@@ -734,11 +736,17 @@ export async function refuseEmailOutsideSso(return refusal ? ctx.error("rule", refusal) : null;}+/**+ * Accepts an invite and records it: an audit entry (with the request's IP and+ * user agent when `request` is given) and, on Cloud, the seat count. The invite+ * page and /callback both accept through here.+ */export async function acceptInvite(serviceRole: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,code: string,- email?: string+ email?: string,+ request?: Request) {const invite = await serviceRole.from("invite")@@ -951,6 +959,42 @@ export async function acceptInvite();}+ // Best-effort audit of the acceptance, with request metadata.+ try {+ await insertAuditLogEntries(serviceRole, companyId, [+ {+ tableName: "invite",+ entityType: "invite",+ entityId: acceptedInvite.id,+ recordId: acceptedInvite.id,+ operation: "UPDATE",+ actorId: null,+ diff: { acceptedAt: { old: null, new: acceptedInvite.acceptedAt } },+ metadata: {+ ipAddress: request+ ? (getClientIp(request) ?? undefined)+ : undefined,+ userAgent: request?.headers.get("user-agent") ?? undefined+ }+ }+ ]);+ } catch (err) {+ logger.warn("[invite] audit write skipped for accept", { error: err });+ }++ // The invite is accepted by now: a billing failure must not report it as+ // not accepted.+ if (CarbonEdition === Edition.Cloud) {+ try {+ await updateSubscriptionQuantityForCompany(companyId);+ } catch (err) {+ logger.error("Failed to update seats after invite accept", {+ error: err,+ companyId+ });+ }+ }+return { data: acceptedInvite, error: null };} catch (err) {logger.error("Failed to accept invite", { error: err, userId, companyId });diff --git a/apps/erp/app/routes/_public+/callback.tsx b/apps/erp/app/routes/_public+/callback.tsxindex 90a00bf38e..d72f39ed42 100644--- a/apps/erp/app/routes/_public+/callback.tsx+++ b/apps/erp/app/routes/_public+/callback.tsx@@ -56,6 +56,7 @@ import {getCompanies,getEmployeeCompanies} from "~/modules/settings/settings.service";+import { acceptInvite } from "~/modules/users/users.service";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";@@ -88,11 +89,16 @@ export async function action({ request }: ActionFunctionArgs) {// Pre-session: no user-authed client yet, so query memberships with the// service role. Prefer an employee company as the active one; fall back to// any membership so auth/RLS can deny a pure portal user later.- const employeeCompanies =- (await getEmployeeCompanies(serviceRole, userId)).data ?? [];+ const employeeLookup = await getEmployeeCompanies(serviceRole, userId);+ const employeeCompanies = employeeLookup.data ?? [];+ const companyLookup = employeeCompanies.length+ ? null+ : await getCompanies(serviceRole, userId);const pickable = employeeCompanies.length? employeeCompanies- : ((await getCompanies(serviceRole, userId)).data ?? []);+ : (companyLookup?.data ?? []);+ // A failed read is not "no company": nothing is accepted on its say-so.+ const membershipKnown = !employeeLookup.error && !companyLookup?.error;const cookieCompanyId = getCompanyId(request);const match =@@ -456,6 +462,53 @@ export async function action({ request }: ActionFunctionArgs) {prefix: SIGN_IN_CODE_LOCKOUT_PREFIX}).reset(authSession.email);+ // An invitee who signs in from the sign-in page, not the invite's Accept+ // button, arrives with no company and the invite still open, and the+ // shell sends a company-less user to onboarding. Signing in proved the+ // invited address, so accept the invite here, as the SSO path does.+ if (pickable.length === 0 && membershipKnown) {+ const pendingInvite = await serviceRole+ .from("invite")+ .select("code")+ .ilike(+ "email",+ authSession.email.replace(/[\\%_]/g, (match) => `\\${match}`)+ )+ .is("acceptedAt", null)+ .is("revokedAt", null)+ .order("createdAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (pendingInvite.data) {+ const accept = await acceptInvite(+ serviceRole,+ getDatabaseClient(),+ pendingInvite.data.code,+ authSession.email,+ request+ ).catch((err: unknown) => ({+ data: null,+ error: { message: String(err) }+ }));++ if (accept.data) {+ const company = await serviceRole+ .from("company")+ .select("companyGroupId")+ .eq("id", accept.data.companyId)+ .maybeSingle();+ authSession.companyId = accept.data.companyId;+ authSession.companyGroupId = company.data?.companyGroupId ?? "";+ } else {+ logger.error("Failed to accept a pending invite on sign-in", {+ error: accept.error,+ userId: authSession.userId+ });+ }+ }+ }+// TOTP gate: park the tokens in the pending-MFA key and challenge before// any full session cookie exists. The /mfa action mints the real session.if (await userHasVerifiedTotpFactor(authSession.userId)) {diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsxindex ba16fa6c88..1b27af9f30 100644--- a/apps/erp/app/routes/_public+/invite.$code.tsx+++ b/apps/erp/app/routes/_public+/invite.$code.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import {- CarbonEdition,CONTROLLED_ENVIRONMENT,error,getAppUrl,@@ -18,15 +17,11 @@ import {updateCompanySession} from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";-import { insertAuditLogEntries } from "@carbon/ee/audit.server";import { Ratelimit, redis } from "@carbon/kv";import { sendEmail } from "@carbon/lib/email.server";-import { getLogger } from "@carbon/logger";import { Button as _Button, Heading as _Heading, VStack } from "@carbon/react";-import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";import {datetime,- Edition,getClientIp,redirect,redirectExternal@@ -48,8 +43,6 @@ import {import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";-const logger = getLogger("erp", "invite");-export const meta: MetaFunction = () => {return [{ title: "Accept Invite | Carbon" }];};@@ -101,7 +94,8 @@ export async function action({ request, params }: ActionFunctionArgs) {serviceRole,getDatabaseClient(),code,- authSession?.email+ authSession?.email,+ request);if (accept.error) {throw redirect(@@ -113,31 +107,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- // Best-effort audit of the acceptance, with request metadata.- try {- await insertAuditLogEntries(serviceRole, accept.data.companyId, [- {- tableName: "invite",- entityType: "invite",- entityId: accept.data.id,- recordId: accept.data.id,- operation: "UPDATE",- actorId: null,- diff: { acceptedAt: { old: null, new: accept.data.acceptedAt } },- metadata: {- ipAddress: getClientIp(request) ?? undefined,- userAgent: request.headers.get("user-agent") ?? undefined- }- }- ]);- } catch (err) {- logger.warn("[invite] audit write skipped for accept", { error: err });- }-- if (CarbonEdition === Edition.Cloud) {- await updateSubscriptionQuantityForCompany(accept.data.companyId);- }-if (authSession) {await redis.del(getPermissionCacheKey(authSession.userId));