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
// 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 { Edition } from "@carbon/utils";
import { createCookieSessionStorage } from "react-router";
import { CarbonEdition, DOMAIN, SESSION_SECRET } from "../config/env";
import { authCookieName, getCookieDomain } from "../utils/cookie";
// Long enough to outlive an integrations page left open for a while: the state
// is issued when the page loads, not when Connect is clicked. It is single-use
// and bound to integration + user + company, so the lifetime is not what
// protects it.
const OAUTH_STATE_MAX_AGE_SECONDS = 60 * 60;
// A still-valid state with at least this much life left is handed out again
// instead of being replaced, so two tabs of the integrations page (or a page
// revalidation) do not invalidate each other's Connect links.
const OAUTH_STATE_REUSE_MIN_REMAINING_MS =
(OAUTH_STATE_MAX_AGE_SECONDS * 1000) / 2;
// One entry per integration, so several connect flows can be in flight at once.
const OAUTH_STATES_KEY = "oauth-states";
// The pre-keyed shape held a single state; read it so a flow started before
// the upgrade still completes.
const LEGACY_OAUTH_STATE_KEY = "oauth-state";
export type OAuthStatePayload = {
integrationId: string;
userId: string;
companyId: string;
};
/**
* Extra fields carried THROUGH the round trip rather than matched on it.
*
* `mode` decides which scopes were requested, so it must survive the redirect to
* be stamped on the install afterwards — and it must travel in the SIGNED,
* HttpOnly cookie, never a query parameter. A user-editable mode would let
* someone consent to push-only's narrow scopes and have Carbon record the install
* as provider mode, or the reverse.
*
* It is deliberately NOT part of the match: the callback has no independent copy
* to compare against, so "matching" it would only compare the cookie to itself.
*
* `name` and `connectionId` are the same kind of field for a workflow piece: the
* account the consent is saved under, and the one row a Reconnect revives.
*/
export type OAuthStateExtras = {
mode?: string;
name?: string;
connectionId?: string;
};
type StoredOAuthState = OAuthStatePayload &
OAuthStateExtras & {
state: string;
expiresAt: number;
};
type StoredOAuthStates = Record<string, StoredOAuthState>;
function extrasOf(stored: StoredOAuthState): OAuthStateExtras {
return {
mode: stored.mode,
name: stored.name,
connectionId: stored.connectionId
};
}
/** A state issued for other extras is never handed to a connect for these. */
function sameExtras(a: OAuthStateExtras, b: OAuthStateExtras) {
return (
a.mode === b.mode && a.name === b.name && a.connectionId === b.connectionId
);
}
const isTestEdition = CarbonEdition === Edition.Test;
const cookieDomain = isTestEdition ? undefined : getCookieDomain(DOMAIN);
const oauthStateStorage = createCookieSessionStorage({
cookie: {
name: authCookieName("carbon-oauth-state"),
httpOnly: true,
path: "/",
sameSite: isTestEdition ? "none" : "lax",
secrets: [SESSION_SECRET!],
secure: isTestEdition || !!cookieDomain,
domain: cookieDomain,
maxAge: OAUTH_STATE_MAX_AGE_SECONDS
}
});
type OAuthStateSession = Awaited<
ReturnType<typeof oauthStateStorage.getSession>
>;
function isStoredOAuthState(value: unknown): value is StoredOAuthState {
if (!value || typeof value !== "object") return false;
const v = value as Record<string, unknown>;
return (
typeof v.state === "string" &&
typeof v.integrationId === "string" &&
typeof v.userId === "string" &&
typeof v.companyId === "string" &&
typeof v.expiresAt === "number"
);
}
/** The live (unexpired) states in the session, keyed by integration. */
function readStates(session: OAuthStateSession): StoredOAuthStates {
const states: StoredOAuthStates = {};
const now = Date.now();
const legacy = session.get(LEGACY_OAUTH_STATE_KEY);
if (isStoredOAuthState(legacy) && legacy.expiresAt > now) {
states[legacy.integrationId] = legacy;
}
const stored = session.get(OAUTH_STATES_KEY);
if (stored && typeof stored === "object") {
for (const [integrationId, value] of Object.entries(stored)) {
if (
isStoredOAuthState(value) &&
value.integrationId === integrationId &&
value.expiresAt > now
) {
states[integrationId] = value;
}
}
}
return states;
}
async function commitStates(
session: OAuthStateSession,
states: StoredOAuthStates
) {
session.unset(LEGACY_OAUTH_STATE_KEY);
if (Object.keys(states).length === 0) {
return oauthStateStorage.destroySession(session);
}
session.set(OAUTH_STATES_KEY, states);
return oauthStateStorage.commitSession(session, {
maxAge: OAUTH_STATE_MAX_AGE_SECONDS
});
}
/**
* Issue a state per payload, keeping every other integration's pending state
* already in the request's cookie. Returns the states keyed by integration id
* and ONE Set-Cookie value that carries all of them.
*/
export async function issueOAuthStates(
request: Request | null,
payloads: Array<OAuthStatePayload & OAuthStateExtras>
) {
const session = await oauthStateStorage.getSession(
request?.headers.get("Cookie")
);
const states = readStates(session);
const now = Date.now();
const issued: Record<string, string> = {};
for (const payload of payloads) {
const existing = states[payload.integrationId];
const reusable =
!!existing &&
existing.userId === payload.userId &&
existing.companyId === payload.companyId &&
// The extras ride the cookie to be acted on by the callback, so a state
// issued for one mode (or account) must never serve a connect for another.
sameExtras(existing, payload) &&
existing.expiresAt - now >= OAUTH_STATE_REUSE_MIN_REMAINING_MS;
if (reusable) {
issued[payload.integrationId] = existing.state;
continue;
}
const state = crypto.randomUUID();
states[payload.integrationId] = {
...payload,
state,
expiresAt: now + OAUTH_STATE_MAX_AGE_SECONDS * 1000
};
issued[payload.integrationId] = state;
}
return {
states: issued,
cookie: await commitStates(session, states)
};
}
/**
* Issue one integration's state. Pass the request so other integrations'
* pending states in its cookie survive the new Set-Cookie.
*/
export async function issueOAuthState(
payload: OAuthStatePayload & OAuthStateExtras,
request: Request | null = null
) {
const { states, cookie } = await issueOAuthStates(request, [payload]);
return { state: states[payload.integrationId]!, cookie };
}
/**
* Remove the entry `find` picks and say whether it is valid for `state` and the
* session's user and company. Single-use whether or not it matched; every other
* pending entry is left in place.
*/
async function consumeStoredState(
request: Request,
state: string,
owner: Pick<OAuthStatePayload, "userId" | "companyId">,
find: (states: StoredOAuthStates) => StoredOAuthState | undefined
) {
const session = await oauthStateStorage.getSession(
request.headers.get("Cookie")
);
const states = readStates(session);
const stored = find(states);
const valid =
!!stored &&
!!state &&
stored.expiresAt > Date.now() &&
stored.state === state &&
stored.userId === owner.userId &&
stored.companyId === owner.companyId;
if (stored) delete states[stored.integrationId];
return {
valid,
cookie: await commitStates(session, states),
// Only a VALID entry leaves this function: an invalid one would hand the
// caller attacker-supplied values that passed no check.
stored: valid ? stored : undefined
};
}
/**
* Check a callback's `state` against the one stored for `expected.integrationId`
* and remove it — single-use whether or not it matched. Other integrations'
* pending states are left in place.
*/
export async function consumeOAuthState(
request: Request,
state: string,
expected: OAuthStatePayload
) {
const { valid, cookie, stored } = await consumeStoredState(
request,
state,
expected,
(states) => states[expected.integrationId]
);
return {
valid,
cookie,
/** The stored extras, for fields the callback cannot re-derive — only when
* the state was VALID. */
payload: stored ? extrasOf(stored) : undefined
};
}
/**
* For a callback shared by several integrations (the workflow pieces' one
* redirect URI), which cannot know the integration before reading the state:
* find the pending entry holding `state`, check it like `consumeOAuthState`, and
* remove it. The payload names the integration, only when the state was valid.
*/
export async function consumeOAuthStateByValue(
request: Request,
state: string,
owner: Pick<OAuthStatePayload, "userId" | "companyId">
) {
const { valid, cookie, stored } = await consumeStoredState(
request,
state,
owner,
(states) => Object.values(states).find((entry) => entry.state === state)
);
return {
valid,
cookie,
payload: stored
? { integrationId: stored.integrationId, ...extrasOf(stored) }
: undefined
};
}