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.

fix(api): gate MCP OAuth callers on their user's permissions and harden the OAuth server (#1905)

Brad Barbin0762db0c9650
diff --git a/.ai/lessons.md b/.ai/lessons.md
index e4c2bc6eda..a0d3227f33 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3546,3 +3546,14 @@ A ✓ that a script prints after a step that is allowed to fail is not evidence.
**Rule:** When you add an entity to `audit.config.ts`, give each of its tables `events: true` in `attachments.ts` and ship it with `pnpm --filter @carbon/database authz migration <name>`. To debug an empty audit log, first check `pg_trigger` for `trg_event_async_*` on the table.
**Applies to:** `packages/database/src/audit.config.ts`, `packages/database/src/event-system/attachments.ts`.
+
+## RLS does not bound an MCP tool handed `db`; its declared permission is the only gate
+
+**Context:** A 2026-10 security disclosure: an OAuth (MCP connector) token for a user with no accounting permission could create draft GL journals through `inventory_createInventoryReconciliationJournal`.
+
+**Problem:** Two gaps stacked. The oRPC `gate()` skipped OAuth callers on the theory that RLS bounds them, but a service whose manifest asks for `db` gets `getDatabaseClient()`, the direct connection, which bypasses RLS. And a tool's default permission is its own module plus its verb's action, so the journal tool was gated on `inventory:create` while the Reconcile screen requires `accounting:create`. Supplier and customer bank accounts (`purchasing`/`sales` vs `accounting`) and return-order credits (`purchasing`/`sales` vs `invoicing`) had the same mismatch, for API keys as well.
+
+**Rule:** Every non-session caller (API key AND OAuth) is gated per operation, OAuth on the user's live permissions in the token's company (`scopesFromPermissions`). When a tool does what an ERP route does, its permission must equal that route's `requirePermissions`: add `@mcp permission` where the default differs, regenerate, and pin it in `OVERRIDES` in `mcp-tool-permissions.test.ts`. Never reason "RLS will catch it" for a tool whose `contextParams` include `db`.
+
+**Applies to:** `apps/erp/app/routes/api+/v1+/lib/base.server.ts`, `apps/erp/app/routes/api+/mcp+/_index.ts`, every `@mcp`-tagged service taking `db: Kysely<KyselyDatabase>`.
+
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index 006df134eb..c578a4e6ad 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -447,17 +447,36 @@ ERP exposes an OAuth 2.0 AS for use as a remote Claude/MCP connector. Routes und
`_oauth+/` (`authorize.tsx`, `token.tsx`, `register.ts`) plus discovery at
`[.]well-known.oauth-authorization-server.ts` and `[.]well-known.oauth-protected-resource.ts`.
-- PKCE supported (`code_challenge` / `code_challenge_method` S256|plain on authorize,
- `code_verifier` on token).
+- PKCE: `code_challenge` on authorize (required for public clients), verified S256-only
+ with `code_verifier` on token.
- Dynamic client registration (`POST /oauth/register`) writes to the **`oauthClient`**
- table. <!-- UNVERIFIED: the old cache doc described a separate `oauthDynamicClient` table; it does not exist in current migrations. -->
+ table. It is open by design (MCP clients self-register) but rate-limited per IP
+ (100/hour), and the rules live in `~/services/oauth.server.ts`:
+ `isAllowedRedirectUri` admits https, http only on a loopback host, or a
+ private-use scheme, never a fragment; `supportedScope` keeps only `mcp:tools`.
+ Only `client_secret_post` and `none` are accepted as `token_endpoint_auth_method`
+ (what discovery advertises; `/token` never reads a Basic header).
+- **Authorize** (`authorize.tsx`) requires `settings_update` and employee role in the
+ SELECTED company (`canAuthorizeForCompany`), not just the session's active one, and
+ re-checks the redirect URI with `isRegisteredRedirectUri` (registered AND still
+ allowed — clients registered before the rules existed are held to them too). The
+ consent page shows the redirect host only once it passes that check.
+- **Refresh tokens rotate** on every use (the update matches the OLD hash, so one of
+ two concurrent refreshes loses) and die after 30 days idle (`isRefreshTokenIdle`:
+ `expiresAt` + 30 days — no extra column). There is no revocation endpoint.
+- A token carries no permissions of its own: the MCP endpoint re-checks on every
+ request that the user is still an `employee` of the token's company and gates each
+ operation on that user's live permissions (see `mcp-tools-reference.md`).
- Tables: `oauthClient`, `oauthCode`, `oauthToken` (all PK `xid()`, scoped by
`companyId`/`userId`). Columns are plain TEXT, but **access tokens, refresh tokens, and
client secrets are SHA-256 hashed at the app layer before storage** via
`hashOAuthSecret` (`auth.server.ts`). Lookups hash the incoming value and compare.
-- MCP endpoint (`apps/erp/app/routes/api+/mcp+/_index.ts`): a `Bearer` token (when no
- `carbon-key`) is hashed and looked up in `oauthToken`; on miss it falls back to
- `carbon-key` API-key auth. `companyId`/`userId` always come from the token context.
+- MCP endpoint (`apps/erp/app/routes/api+/mcp+/_index.ts`): a `Bearer` token not
+ prefixed `crbn_` is an OAuth token — `findOAuthToken` (hash lookup + expiry), the
+ per-user rate limit, then `oauthContext` (membership, company group, claims, user
+ client, in parallel), both in `api+/v1+/lib/authenticate.server.ts` beside
+ `authenticateApiKey`. A `crbn_` bearer is rewritten to `carbon-key` API-key auth.
+ `companyId`/`userId` always come from the token row.
## Schema (newest migrations; `packages/database/supabase/migrations`)
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 106615022a..fdafb4031d 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -256,8 +256,13 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate
- `callOperation` resolves the manifest entry (`operationsByName`) and runs the
real oRPC procedure via server-side `call()` — gate middleware included, so an
**API-key** caller is scope-checked per operation (403 when the key lacks
- `<module>_<action>` for the company). OAuth-connector and in-process
- (`authKind: "session"`) callers skip the scope gate; RLS/role bounds them.
+ `<module>_<action>` for the company). An **OAuth-connector** caller is gated
+ the same way, on scopes built from its user's live permissions in the token's
+ company (`scopesFromPermissions`, `base.server.ts`). RLS cannot bound it: a
+ service handed `db` writes through the direct connection, which bypasses RLS,
+ so before this a connector token for a user with no accounting permission
+ could write GL journals. Only the in-process workflow engine
+ (`authKind: "session"`) skips the gate.
- The service registry lives at `api+/v1+/lib/registry.server.ts` (the 15 module
namespaces); the arg assembly lives in `api+/v1+/lib/dispatch.server.ts`.
- **Input is validated** against the operation's own schema before dispatch.
@@ -458,7 +463,7 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc
| Line | Meaning |
|---|---|
| `@mcp <verb> [destructive]` | Required, exactly once. No such line → not a tool, reads included. Text after it is a note. |
- | `@mcp permission <module>:<action>[+<action>]` | Only when the gate is not the tool's own module + its verb's action (`getApiKeys` → `users:update`). |
+ | `@mcp permission <module>:<action>[+<action>]` | Only when the gate is not the tool's own module + its verb's action (`getApiKeys` → `users:update`). REQUIRED when the ERP route doing the same thing requires a different module: a supplier bank account is `accounting`, not `purchasing`; a return-order credit is `invoicing`. Pinned in `apps/erp/test/mcp-tool-permissions.test.ts` (`OVERRIDES`). |
| `@mcp audit <field>[, <field>]` | Only when the verb's audit fields are wrong for intent the schema cannot express (a ledger insert takes `createdBy` alone). Stated in full; `companyId` is always added. |
| `@mcp key <table> <column>[=<field>], …` | The row an upsert updates when it exists (below). Several lines are alternatives. |
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 104d6e4f18..56bdf1dc26 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -430,7 +430,14 @@ export async function getInventoryValuationTieOut(
// Posted on the tie-out's as-of date — the tie-out only counts journals with
// postingDate <= asOfDate, so a today-dated journal could never resolve a
// backdated variance. Posting may still be rejected if that period is Closed.
-/** @mcp create */
+/**
+ * Creates a draft GL journal that clears the inventory valuation variance.
+ *
+ * Gated on accounting, as the Reconcile screen is: it writes a journal, not
+ * inventory.
+ * @mcp create
+ * @mcp permission accounting:create
+ */
export async function createInventoryReconciliationJournal(
client: SupabaseClient<Database>,
db: Kysely<KyselyDatabase>,
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 8bea50a429..0d75a74344 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -345,7 +345,10 @@ export async function deleteSupplierLocation(
}
}
-/** @mcp delete */
+/**
+ * @mcp delete
+ * @mcp permission accounting:delete
+ */
export async function deleteSupplierBankAccount(
client: SupabaseClient<Database>,
id: string
@@ -353,7 +356,14 @@ export async function deleteSupplierBankAccount(
return client.from("supplierBankAccount").delete().eq("id", id);
}
-/** @mcp read */
+/**
+ * Lists a supplier's bank accounts.
+ *
+ * Gated on accounting, as the table's RLS and every bank-account screen are:
+ * a changed payee account is how payment fraud starts.
+ * @mcp read
+ * @mcp permission accounting:view
+ */
export async function getSupplierBankAccounts(
client: SupabaseClient<Database>,
supplierId: string
@@ -365,7 +375,10 @@ export async function getSupplierBankAccounts(
.order("name");
}
-/** @mcp upsert */
+/**
+ * @mcp upsert
+ * @mcp permission accounting:create+update
+ */
export async function upsertSupplierBankAccount(
db: Kysely<KyselyDatabase>,
bankAccount:
@@ -4794,6 +4807,7 @@ export async function getCreditableQuantitiesForPurchaseReturn(
* `direction = "Debit"`, so a Credit-direction memo here is also invisible to
* "Apply Credit" on a supplier invoice.
* @mcp create
+ * @mcp permission invoicing:create
* @mcp audit companyGroupId, createdBy, updatedBy, userId
*/
export async function createPurchaseReturnOrderCredit(
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index e3c7f63c5a..2db5180156 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -352,7 +352,10 @@ export async function deleteCustomer(
return client.from("customer").delete().eq("id", customerId);
}
-/** @mcp delete */
+/**
+ * @mcp delete
+ * @mcp permission accounting:delete
+ */
export async function deleteCustomerBankAccount(
client: SupabaseClient<Database>,
id: string
@@ -360,7 +363,14 @@ export async function deleteCustomerBankAccount(
return client.from("customerBankAccount").delete().eq("id", id);
}
-/** @mcp read */
+/**
+ * Lists a customer's bank accounts.
+ *
+ * Gated on accounting, as the table's RLS and every bank-account screen are:
+ * a changed payee account is how payment fraud starts.
+ * @mcp read
+ * @mcp permission accounting:view
+ */
export async function getCustomerBankAccounts(
client: SupabaseClient<Database>,
customerId: string
@@ -372,7 +382,10 @@ export async function getCustomerBankAccounts(
.order("name");
}
-/** @mcp upsert */
+/**
+ * @mcp upsert
+ * @mcp permission accounting:create+update
+ */
export async function upsertCustomerBankAccount(
db: Kysely<KyselyDatabase>,
bankAccount:
@@ -8036,6 +8049,7 @@ export async function getCreditableQuantities(
* transaction under a row lock on the RMA lines. Amount is rounded ONCE at
* the currency's decimals (settlement boundary). Returns the memo id.
* @mcp create
+ * @mcp permission invoicing:create
* @mcp audit companyGroupId, createdBy, updatedBy, userId
*/
export async function createSalesReturnOrderCredit(
diff --git a/apps/erp/app/routes/_oauth+/authorize.tsx b/apps/erp/app/routes/_oauth+/authorize.tsx
index d5f24c5dd0..d69c3e7b90 100644
--- a/apps/erp/app/routes/_oauth+/authorize.tsx
+++ b/apps/erp/app/routes/_oauth+/authorize.tsx
@@ -4,51 +4,63 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getUserClaims } from "@carbon/auth/users.server";
import { validator } from "@carbon/form";
import { Button, Heading, VStack } from "@carbon/react";
import { redirectExternal } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, Form, useLoaderData } from "react-router";
import { z } from "zod";
+import {
+ canAuthorizeForCompany,
+ isRegisteredRedirectUri,
+ supportedScope
+} from "~/services/oauth.server";
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
update: "settings"
});
- const userCompanies = await client
- .from("userToCompany")
- .select("companyId, company:companyId(name)")
- .eq("userId", userId);
+ const [userCompanies, claims] = await Promise.all([
+ client
+ .from("userToCompany")
+ .select("companyId, role, company:companyId(name)")
+ .eq("userId", userId),
+ getUserClaims(userId, companyId)
+ ]);
- const companies = (userCompanies.data ?? []).map((uc) => ({
- id: uc.companyId,
- name: (uc.company as unknown as { name: string })?.name ?? uc.companyId
- }));
+ // Only the companies the user may authorize a connector for.
+ const companies = (userCompanies.data ?? [])
+ .filter((uc) => canAuthorizeForCompany(uc, claims.permissions))
+ .map((uc) => ({
+ id: uc.companyId,
+ name: (uc.company as unknown as { name: string })?.name ?? uc.companyId
+ }));
const url = new URL(request.url);
const clientId = url.searchParams.get("client_id");
const redirectUri = url.searchParams.get("redirect_uri");
- const scope = url.searchParams.get("scope");
+ const scope = supportedScope(url.searchParams.get("scope"));
+ // The name is whatever the client registered itself as, so the page also
+ // shows where the code goes — the one thing a client cannot choose freely —
+ // and only once it matches a registered redirect URI.
let clientName = "Unknown Application";
let redirectDomain: string | null = null;
if (clientId) {
const serviceRole = getCarbonServiceRole();
const oauthClient = await serviceRole
.from("oauthClient")
- .select("name")
+ .select("name, redirectUris")
.eq("clientId", clientId)
.single();
if (oauthClient.data) {
clientName = oauthClient.data.name;
- }
- }
- if (redirectUri) {
- try {
- redirectDomain = new URL(redirectUri).hostname;
- } catch {
- // invalid URL — will be caught by the action validator
+ if (isRegisteredRedirectUri(oauthClient.data.redirectUris, redirectUri)) {
+ const target = new URL(redirectUri);
+ redirectDomain = target.host || target.protocol;
+ }
}
}
@@ -66,7 +78,7 @@ const formValidator = z.object({
});
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "settings"
});
@@ -89,7 +101,7 @@ export async function action({ request }: ActionFunctionArgs) {
const client_id = param("client_id");
const redirect_uri = url.searchParams.get("redirect_uri");
const state = url.searchParams.get("state");
- const scope = url.searchParams.get("scope");
+ const scope = supportedScope(url.searchParams.get("scope"));
const code_challenge = param("code_challenge");
const code_challenge_method = param("code_challenge_method");
@@ -107,15 +119,22 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- // Verify the user belongs to the selected company
- const membership = await client
- .from("userToCompany")
- .select("companyId")
- .eq("userId", userId)
- .eq("companyId", company_id)
- .single();
+ // The token acts in the SELECTED company, so the user must be able to
+ // authorize there — requirePermissions above only checked the active one.
+ const [membership, claims] = await Promise.all([
+ client
+ .from("userToCompany")
+ .select("companyId, role")
+ .eq("userId", userId)
+ .eq("companyId", company_id)
+ .single(),
+ getUserClaims(userId, companyId)
+ ]);
- if (!membership.data) {
+ if (
+ !membership.data ||
+ !canAuthorizeForCompany(membership.data, claims.permissions)
+ ) {
return data({ error: "Invalid company" }, { status: 403 });
}
@@ -133,7 +152,7 @@ export async function action({ request }: ActionFunctionArgs) {
const oauthClient = oauthClientResult.data;
- if (!oauthClient.redirectUris.includes(redirect_uri)) {
+ if (!isRegisteredRedirectUri(oauthClient.redirectUris, redirect_uri)) {
return data({ error: "Invalid redirect URI" }, { status: 400 });
}
@@ -150,7 +169,7 @@ export async function action({ request }: ActionFunctionArgs) {
userId,
companyId: company_id,
redirectUri: redirect_uri,
- scope: scope || null,
+ scope,
codeChallenge: code_challenge || null,
codeChallengeMethod: code_challenge_method || null,
createdAt: new Date().toISOString(),
@@ -207,6 +226,11 @@ export default function AuthorizeRoute() {
)}{" "}
is requesting access to your Carbon account.
</p>
+ <p className="text-center text-xs text-pretty text-muted-foreground">
+ The application names itself. Only authorize it if you started
+ this connection. It will be able to do anything you can do in
+ the company you choose.
+ </p>
<div className="flex w-full flex-col gap-1.5">
<label
htmlFor="company_id"
diff --git a/apps/erp/app/routes/_oauth+/register.ts b/apps/erp/app/routes/_oauth+/register.ts
index 053750007e..74d57a0ef3 100644
--- a/apps/erp/app/routes/_oauth+/register.ts
+++ b/apps/erp/app/routes/_oauth+/register.ts
@@ -4,9 +4,12 @@
import { hashOAuthSecret } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { Ratelimit, redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
+import { getClientIp } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { z } from "zod";
+import { isAllowedRedirectUri, supportedScope } from "~/services/oauth.server";
const logger = getLogger("erp", "register");
@@ -24,21 +27,37 @@ function jsonResponse(body: unknown, status: number = 200) {
});
}
+// Registration is open by design — MCP clients (Claude, Cursor, VS Code) register
+// themselves on first connect, with no account to authenticate. So the limit is
+// per IP and generous: a connector platform registers from a few egress IPs.
+const REGISTRATIONS_PER_HOUR = 100;
+
const clientRegistrationSchema = z.object({
- client_name: z.string().min(1),
- redirect_uris: z.array(z.string().url()).min(1),
+ client_name: z.string().trim().min(1).max(100),
+ redirect_uris: z
+ .array(
+ z.string().max(2000).refine(isAllowedRedirectUri, {
+ message:
+ "redirect_uris must be https, http on a loopback address, or a private-use scheme, with no fragment"
+ })
+ )
+ .min(1)
+ .max(10),
grant_types: z
- .array(z.string())
+ .array(z.enum(["authorization_code", "refresh_token"]))
.optional()
.default(["authorization_code", "refresh_token"]),
- response_types: z.array(z.string()).optional().default(["code"]),
+ response_types: z.array(z.literal("code")).optional().default(["code"]),
+ // What `/.well-known/oauth-authorization-server` advertises: `/token` reads
+ // the secret from the form body only, so a `client_secret_basic` client
+ // could register and then never authenticate.
token_endpoint_auth_method: z
- .enum(["client_secret_post", "client_secret_basic", "none"])
+ .enum(["client_secret_post", "none"])
.optional()
.default("none"),
- client_uri: z.string().url().optional(),
- logo_uri: z.string().url().optional(),
- scope: z.string().optional()
+ client_uri: z.string().url().max(2000).optional(),
+ logo_uri: z.string().url().max(2000).optional(),
+ scope: z.string().max(500).optional()
});
export async function loader({ request }: LoaderFunctionArgs) {
@@ -51,7 +70,24 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
+const registerRatelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(REGISTRATIONS_PER_HOUR, "1 h")
+});
+
export async function action({ request }: ActionFunctionArgs) {
+ const ip = getClientIp(request) ?? "unknown";
+ const rl = await registerRatelimit.limit(`oauth-register:${ip}`);
+ if (!rl.success) {
+ return jsonResponse(
+ {
+ error: "too_many_requests",
+ error_description: "Too many client registrations. Try again later."
+ },
+ 429
+ );
+ }
+
const client = getCarbonServiceRole();
let body: unknown;
@@ -84,9 +120,9 @@ export async function action({ request }: ActionFunctionArgs) {
response_types,
token_endpoint_auth_method,
client_uri,
- logo_uri,
- scope
+ logo_uri
} = validation.data;
+ const scope = supportedScope(validation.data.scope);
// Generate client credentials
const clientId = `mcp_${crypto.randomUUID().replace(/-/g, "")}`;
diff --git a/apps/erp/app/routes/_oauth+/token.tsx b/apps/erp/app/routes/_oauth+/token.tsx
index 1eec75a7fc..f7200dd6bc 100644
--- a/apps/erp/app/routes/_oauth+/token.tsx
+++ b/apps/erp/app/routes/_oauth+/token.tsx
@@ -8,6 +8,10 @@ import { validator } from "@carbon/form";
import { createHash } from "crypto";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { z } from "zod";
+import {
+ ACCESS_TOKEN_TTL_MS,
+ isRefreshTokenIdle
+} from "~/services/oauth.server";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -209,8 +213,9 @@ export async function action({ request }: ActionFunctionArgs) {
clientId: client_id,
userId: codeData.userId,
companyId: codeData.companyId,
+ scope: codeData.scope,
createdAt: new Date().toISOString(),
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString()
+ expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS).toISOString()
};
const tokenResult = await client.from("oauthToken").insert([tokenInsert]);
@@ -225,7 +230,7 @@ export async function action({ request }: ActionFunctionArgs) {
return jsonResponse({
access_token: rawAccessToken,
token_type: "Bearer",
- expires_in: 3600,
+ expires_in: ACCESS_TOKEN_TTL_MS / 1000,
refresh_token: rawRefreshToken,
scope: codeData.scope || undefined
});
@@ -266,16 +271,30 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- // Generate new access token
+ if (isRefreshTokenIdle(refreshTokenData.expiresAt, Date.now())) {
+ await client.from("oauthToken").delete().eq("id", refreshTokenData.id);
+ return jsonResponse(
+ { error: "invalid_grant", error_description: "Refresh token expired" },
+ 400
+ );
+ }
+
+ // Rotate: the refresh token is single-use, so a leaked one is only good
+ // until its owner's next refresh. The match on the OLD hash makes this
+ // atomic — of two concurrent refreshes with one token, only one wins.
const rawNewAccessToken = crypto.randomUUID();
+ const rawNewRefreshToken = crypto.randomUUID();
const updateResult = await client
.from("oauthToken")
.update({
accessToken: hashOAuthSecret(rawNewAccessToken),
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString()
+ refreshToken: hashOAuthSecret(rawNewRefreshToken),
+ expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS).toISOString()
})
- .eq("refreshToken", hashOAuthSecret(refresh_token));
+ .eq("id", refreshTokenData.id)
+ .eq("refreshToken", hashOAuthSecret(refresh_token))
+ .select("id");
if (updateResult.error) {
return jsonResponse(
@@ -284,10 +303,18 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ if (!updateResult.data?.length) {
+ return jsonResponse(
+ { error: "invalid_grant", error_description: "Invalid refresh token" },
+ 400
+ );
+ }
+
return jsonResponse({
access_token: rawNewAccessToken,
token_type: "Bearer",
- expires_in: 3600,
+ expires_in: ACCESS_TOKEN_TTL_MS / 1000,
+ refresh_token: rawNewRefreshToken,
scope: refreshTokenData.scope || undefined
});
}
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index 08e95c7517..62939983be 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -3,11 +3,6 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { ManifestEntry } from "@carbon/api";
-import { hashOAuthSecret } from "@carbon/auth/auth.server";
-import {
- getCarbonServiceRole,
- getUserScopedClient
-} from "@carbon/auth/client.server";
import { EntitlementError } from "@carbon/ee/entitlements.server";
import { createCatalogSearch } from "@carbon/ee/mcp";
import { createMcpServer } from "@carbon/ee/mcp.server";
@@ -18,7 +13,11 @@ import { datetime, getRequestOrigin } from "@carbon/utils";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import type { ActionFunctionArgs } from "react-router";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
-import { authenticateApiKey } from "../v1+/lib/authenticate.server";
+import {
+ authenticateApiKey,
+ findOAuthToken,
+ oauthContext
+} from "../v1+/lib/authenticate.server";
import type { AuthedContext } from "../v1+/lib/base.server";
import { callOperation } from "../v1+/lib/call.server";
import {
@@ -54,25 +53,6 @@ function addCorsHeaders(response: Response): Response {
});
}
-async function authenticateOAuthToken(
- accessToken: string
-): Promise<{ userId: string; companyId: string } | null> {
- const serviceRole = getCarbonServiceRole();
- const tokenResult = await serviceRole
- .from("oauthToken")
- .select("userId, companyId, expiresAt")
- .eq("accessToken", hashOAuthSecret(accessToken))
- .single();
-
- if (!tokenResult.data) return null;
- if (new Date(tokenResult.data.expiresAt) < new Date()) return null;
-
- return {
- userId: tokenResult.data.userId,
- companyId: tokenResult.data.companyId
- };
-}
-
/**
* OAuth (connector) callers get 60 requests/minute — what a company's API keys
* get in total — but through the app's Redis limiter rather than the
@@ -144,32 +124,15 @@ async function resolveAuth(request: Request): Promise<{
// Try OAuth for non-API-key tokens
if (!token.startsWith("crbn_")) {
- const oauthAuth = await authenticateOAuthToken(token);
- if (oauthAuth) {
- const rl = await oauthRatelimit.limit(`mcp-oauth:${oauthAuth.userId}`);
+ const identity = await findOAuthToken(token);
+ if (identity) {
+ const rl = await oauthRatelimit.limit(`mcp-oauth:${identity.userId}`);
if (!rl.success) {
throw make429Response(rl.reset, rl.remaining);
}
- const client = await getUserScopedClient(oauthAuth.userId);
- const companyResult = await client
- .from("company")
- .select("companyGroupId")
- .eq("id", oauthAuth.companyId)
- .single();
-
- return {
- ctx: {
- client,
- companyId: oauthAuth.companyId,
- companyGroupId:
- companyResult.data?.companyGroupId ?? oauthAuth.companyId,
- userId: oauthAuth.userId,
- authKind: "oauth" as const,
- scopes: {}
- },
- request
- };
+ const ctx = await oauthContext(identity);
+ if (ctx) return { ctx, request };
}
throw make401Response(request);
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 7321ecef2d..118720a225 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -165,7 +165,7 @@
{"name":"documents_upsertDocument","classification":"WRITE","paramCount":11,"schema":"7b71f5ddd67a","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_cancelOpenPickingListsForJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"844f8eedb019","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},
{"name":"inventory_correctStockMovement","classification":"WRITE","paramCount":3,"schema":"fb389b0474f2","response":"baa524ddff70","injectAuth":"companyId","permission":"inventory:update","paginates":false},
- {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create","paginates":false},
+ {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},
{"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},
{"name":"inventory_deleteInventoryCount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},
{"name":"inventory_deleteKanban","classification":"DESTRUCTIVE","paramCount":1,"schema":"369f807bc840","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},
@@ -846,7 +846,7 @@
{"name":"purchasing_cancelPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},
{"name":"purchasing_confirmPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"purchasing:update","paginates":false},
{"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"16be78b08a8f","response":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},
- {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},
+ {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"invoicing:create","paginates":false},
{"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"11b028f16d94","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},
{"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"a424256cbe29","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},
{"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},
@@ -860,7 +860,7 @@
{"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","paramCount":1,"schema":"4e16cef99961","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deletePurchasingRFQLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"943916e70d0b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deleteSupplier","classification":"DESTRUCTIVE","paramCount":1,"schema":"67043a31b1b5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
- {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
+ {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},
{"name":"purchasing_deleteSupplierContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"041a4bd97ec8","response":"700b93baa3ef","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deleteSupplierLocation","classification":"DESTRUCTIVE","paramCount":2,"schema":"dad5decd6951","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deleteSupplierProcess","classification":"DESTRUCTIVE","paramCount":1,"schema":"fe73a000b6f7","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},
@@ -914,7 +914,7 @@
{"name":"purchasing_getReturnableLinesForSupplier","classification":"READ","paramCount":2,"schema":"7a1204db0d90","response":"24dd6c0d1c55","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
{"name":"purchasing_getSiblingQuotesForQuote","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"cb143b1fe761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
{"name":"purchasing_getSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"10c7209cc38a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
- {"name":"purchasing_getSupplierBankAccounts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"f2b09b60b722","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
+ {"name":"purchasing_getSupplierBankAccounts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"f2b09b60b722","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"purchasing_getSupplierContact","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"6d2aa722b1ce","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
{"name":"purchasing_getSupplierContacts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"e28ccbd2c417","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
{"name":"purchasing_getSupplierInteraction","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"e933ede17ac0","injectAuth":"companyId","permission":"purchasing:view","paginates":false},
@@ -985,7 +985,7 @@
{"name":"purchasing_upsertPurchasingRFQLine","classification":"WRITE","paramCount":1,"schema":"66adf4b67af2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
{"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa459fc25bca","response":"5c9ba5bee3f1","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"context":"createdBy=userId"},
{"name":"purchasing_upsertSupplier","classification":"WRITE","paramCount":10,"schema":"999cedb57790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
- {"name":"purchasing_upsertSupplierBankAccount","classification":"WRITE","paramCount":13,"schema":"cde0d3ca4444","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
+ {"name":"purchasing_upsertSupplierBankAccount","classification":"WRITE","paramCount":13,"schema":"cde0d3ca4444","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},
{"name":"purchasing_upsertSupplierProcess","classification":"WRITE","paramCount":6,"schema":"26d15056f196","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
{"name":"purchasing_upsertSupplierQuoteLine","classification":"WRITE","paramCount":14,"schema":"3c9810ea1df4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
{"name":"purchasing_upsertSupplierType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},
@@ -1181,9 +1181,9 @@
{"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_createPricingRule","classification":"WRITE","paramCount":17,"schema":"8a6a210cb492","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false,"defaults":"always"},
{"name":"sales_createReplacementSalesOrder","classification":"WRITE","paramCount":1,"schema":"f41daa12b05a","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
- {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
+ {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"invoicing:create","paginates":false},
{"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","paramCount":1,"schema":"09e48c79fb16","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
- {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
+ {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},
{"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"3fd22b0165d4","response":"700b93baa3ef","injectAuth":"companyId","permission":"sales:delete","paginates":false},
{"name":"sales_deleteCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
{"name":"sales_deleteCustomerItemRentalRate","classification":"DESTRUCTIVE","paramCount":1,"schema":"ee5e30c7b358","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
@@ -1221,7 +1221,7 @@
{"name":"sales_getContracts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"fc8b89e1366e","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},
{"name":"sales_getCreditableQuantities","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"da2f02c5bdac","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"8642159293c2","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getCustomerBankAccounts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"d8173b9c2e54","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getCustomerBankAccounts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"d8173b9c2e54","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"sales_getCustomerContact","classification":"READ","paramCount":1,"schema":"ad038ec2602b","response":"d16ba475ee9a","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getCustomerContacts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"acc29dbe9746","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getCustomerContractStatuses","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"b4542ed3da5e","injectAuth":"companyId","permission":"sales:view","paginates":false},
@@ -1378,7 +1378,7 @@
{"name":"sales_updateSalesRFQStatus","classification":"WRITE","paramCount":4,"schema":"edf30d1c08da","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_upsertContractLine","classification":"WRITE","paramCount":18,"schema":"7a649c12168f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertCustomer","classification":"WRITE","paramCount":11,"schema":"27fc0d9d8eb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
- {"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"71b1f32160c0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
+ {"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"71b1f32160c0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":10,"schema":"6f67d6ad287a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertCustomerItemRentalRate","classification":"WRITE","paramCount":11,"schema":"d9f007b1b5e5","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertCustomerStatus","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
diff --git a/apps/erp/app/routes/api+/v1+/lib/authenticate.server.ts b/apps/erp/app/routes/api+/v1+/lib/authenticate.server.ts
index be88f50533..a36e17dfc0 100644
--- a/apps/erp/app/routes/api+/v1+/lib/authenticate.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/authenticate.server.ts
@@ -2,18 +2,28 @@
// 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.
-// Resolve an incoming Carbon API v1 request to an AuthedContext.
+// Resolve an incoming Carbon API request to an AuthedContext.
//
// v1 accepts API keys only, sent as `Authorization: Bearer crbn_…` (the convention the
// rest.carbon.ms proxy uses) or the raw `carbon-key` header. Client + rate limit + plan
// gate + expiry are handled by reusing the carbon-key branch of requirePermissions; the
// per-operation scope gate lives in oRPC middleware and reads the scopes we attach here.
+// The MCP endpoint also accepts an OAuth connector token (`authenticateOAuthToken`).
import {
getCompanyIdFromAPIKey,
+ hashOAuthSecret,
requirePermissions
} from "@carbon/auth/auth.server";
-import type { AuthedContext } from "./base.server";
+import {
+ getCarbonServiceRole,
+ getUserScopedClient
+} from "@carbon/auth/client.server";
+import { getUserClaims } from "@carbon/auth/users.server";
+import { getLogger } from "@carbon/logger";
+import { type AuthedContext, scopesFromPermissions } from "./base.server";
+
+const logger = getLogger("erp", "api", "authenticate");
/**
* Authenticate a raw API key into an AuthedContext. Shared by the v1 HTTP
@@ -71,3 +81,76 @@ export async function resolveApiKeyContext(
return authenticateApiKey(request.url, rawKey);
}
+
+/** Who an OAuth access token was issued to, and for which company. */
+export type OAuthIdentity = { userId: string; companyId: string };
+
+/**
+ * The identity behind an OAuth (MCP connector) access token, or null when the
+ * token is unknown or expired. Only the token is read — the caller rate-limits
+ * on the identity before `oauthContext` does the heavier work.
+ */
+export async function findOAuthToken(
+ accessToken: string
+): Promise<OAuthIdentity | null> {
+ const token = await getCarbonServiceRole()
+ .from("oauthToken")
+ .select("userId, companyId, expiresAt")
+ .eq("accessToken", hashOAuthSecret(accessToken))
+ .maybeSingle();
+
+ if (!token.data) return null;
+ if (new Date(token.data.expiresAt) < new Date()) return null;
+ return { userId: token.data.userId, companyId: token.data.companyId };
+}
+
+/**
+ * The AuthedContext an OAuth token acts with, or null when its user may no
+ * longer use it.
+ *
+ * A token carries no permissions of its own. It acts as its user does NOW in
+ * the token's company: an employee there (a user removed from the company, or
+ * turned into a customer/supplier portal account, loses the connector with it),
+ * gated per operation on that user's live permissions.
+ */
+export async function oauthContext({
+ userId,
+ companyId
+}: OAuthIdentity): Promise<AuthedContext | null> {
+ const serviceRole = getCarbonServiceRole();
+ const [membership, company, claims, client] = await Promise.all([
+ serviceRole
+ .from("userToCompany")
+ .select("role")
+ .eq("userId", userId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ serviceRole
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single(),
+ getUserClaims(userId, companyId),
+ getUserScopedClient(userId)
+ ]);
+
+ if (membership.data?.role !== "employee") return null;
+ if (!company.data) {
+ logger.error("Failed to read the OAuth token's company", {
+ companyId,
+ userId,
+ error: company.error
+ });
+ throw new Error(`Failed to read company ${companyId} for an OAuth token`);
+ }
+
+ return {
+ client,
+ companyId,
+ // A company with no group carries "", as a session does.
+ companyGroupId: company.data.companyGroupId ?? "",
+ userId,
+ authKind: "oauth",
+ scopes: scopesFromPermissions(claims.permissions, companyId)
+ };
+}
diff --git a/apps/erp/app/routes/api+/v1+/lib/base.server.ts b/apps/erp/app/routes/api+/v1+/lib/base.server.ts
index 628f71dfd0..0ad91c9891 100644
--- a/apps/erp/app/routes/api+/v1+/lib/base.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/base.server.ts
@@ -5,6 +5,7 @@
// oRPC context + middleware shared by the HTTP transport and the MCP/agent bridges.
import type { ManifestEntry, ToolPermission } from "@carbon/api";
+import type { Permission } from "@carbon/auth";
import type { Database } from "@carbon/database";
import { ORPCError, os } from "@orpc/server";
import type { SupabaseClient } from "@supabase/supabase-js";
@@ -20,13 +21,16 @@ export interface AuthedContext {
userId: string;
companyId: string;
companyGroupId: string;
- /** `"api-key"` runs the per-operation scope gate. `"oauth"` (MCP connector) does
- * not — its RLS/role already bounds it, exactly as MCP behaves today. `"session"`
- * is an already-authorized in-process caller (the in-app agent behind the route's
- * requirePermissions, and the workflow engine acting as the workflow's owner) —
- * not "oauth" because that names a wire protocol, not a trust decision. */
+ /** `"api-key"` and `"oauth"` (MCP connector) both run the per-operation scope
+ * gate. RLS alone does not bound an OAuth caller: a service handed `db` writes
+ * through the direct connection, which bypasses it. `"session"` is an
+ * already-authorized in-process caller (the workflow engine acting as the
+ * workflow's owner) — not "oauth" because that names a wire protocol, not a
+ * trust decision. */
authKind: "api-key" | "oauth" | "session";
- /** The API key's scopes: `{ "<module>_<action>": [companyId, …] }`. */
+ /** `{ "<module>_<action>": [companyId, …] }` — the API key's scopes, or for an
+ * OAuth caller the user's own permissions in the token's company
+ * (`scopesFromPermissions`). */
scopes: Record<string, string[]>;
}
@@ -41,28 +45,59 @@ export const base = os.$context<AuthedContext>();
export function assertScopes(
scopes: Record<string, string[]>,
companyId: string,
- permission: ToolPermission
+ permission: ToolPermission,
+ authKind: Exclude<AuthedContext["authKind"], "session">
): void {
if (permission.module === null) return;
for (const action of permission.actions) {
const key = `${permission.module}_${action}`;
if (!scopes[key]?.includes(companyId)) {
throw new ORPCError("FORBIDDEN", {
- message: `API key lacks the required scope: ${key}`
+ message:
+ authKind === "api-key"
+ ? `API key lacks the required scope: ${key}`
+ : `You do not have the required permission: ${key}`
});
}
}
}
-/** Per-operation gate middleware — runs the scope check for API-key callers.
+/**
+ * A user's permissions (`getUserClaims().permissions`: module → action → company
+ * ids) as the scope map the gate reads, holding only `companyId`. The OAuth
+ * caller's scopes, so a connector token can do exactly what its user can do in
+ * the token's company — no more.
+ */
+export function scopesFromPermissions(
+ permissions: Record<string, Permission>,
+ companyId: string
+): Record<string, string[]> {
+ const scopes: Record<string, string[]> = {};
+ for (const [module, actions] of Object.entries(permissions)) {
+ for (const [action, companyIds] of Object.entries(actions)) {
+ if (companyIds.includes(companyId)) {
+ scopes[`${module}_${action}`] = [companyId];
+ }
+ }
+ }
+ return scopes;
+}
+
+/** Per-operation gate middleware — runs the scope check for API-key and OAuth
+ * callers.
* The blocked-name guard is belt-and-braces: blocked tools are already excluded
* from the manifest at generation time, so this only fires if that exclusion
* ever regresses — the surface stays closed instead of silently opening. */
export const gate = (meta: ManifestEntry) =>
base.middleware(async ({ context, next }) => {
if (isMcpBlockedTool(meta.name)) throw new ORPCError("NOT_FOUND");
- if (context.authKind === "api-key") {
- assertScopes(context.scopes, context.companyId, meta.permission);
+ if (context.authKind !== "session") {
+ assertScopes(
+ context.scopes,
+ context.companyId,
+ meta.permission,
+ context.authKind
+ );
}
return next();
});
diff --git a/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts b/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts
index 63100b3878..becadcfa22 100644
--- a/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/orpc-mechanics.test.ts
@@ -14,7 +14,12 @@ import { OpenAPIGenerator } from "@orpc/openapi";
import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { call } from "@orpc/server";
import { describe, expect, it } from "vitest";
-import { type AuthedContext, base, gate } from "./base.server";
+import {
+ type AuthedContext,
+ base,
+ gate,
+ scopesFromPermissions
+} from "./base.server";
import { outputSchema, shapeHttpBody } from "./operations.server";
import { specOptions } from "./spec-options.server";
@@ -153,11 +158,51 @@ describe("oRPC mechanics for the Carbon API v1 surface", () => {
expect(result).toEqual({ data: "ok" });
});
- it("skips the scope gate for oauth (connector) callers", async () => {
+ // An OAuth connector caller is gated on its user's own permissions. Before
+ // this it skipped the gate, and a service handed `db` (the direct connection,
+ // no RLS) wrote for a user who held no permission for the operation.
+ it("403s an oauth (connector) caller whose user lacks the permission", async () => {
+ await expect(
+ call(router.parts.getParts, {}, { context: ctx({ authKind: "oauth" }) })
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ message: "You do not have the required permission: parts_view"
+ });
+ });
+
+ it("allows an oauth caller whose user holds the permission in the token's company", async () => {
+ const scopes = scopesFromPermissions(
+ { parts: { view: ["c1"], create: [], update: [], delete: [] } },
+ "c1"
+ );
+ const result = await call(
+ router.parts.getParts,
+ {},
+ { context: ctx({ authKind: "oauth", scopes }) }
+ );
+ expect(result).toEqual({ data: "ok" });
+ });
+
+ it("does not let a permission held in another company pass the oauth gate", async () => {
+ const scopes = scopesFromPermissions(
+ { parts: { view: ["c2"], create: [], update: [], delete: [] } },
+ "c1"
+ );
+ expect(scopes).toEqual({});
+ await expect(
+ call(
+ router.parts.getParts,
+ {},
+ { context: ctx({ authKind: "oauth", scopes }) }
+ )
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it("skips the scope gate for in-process session callers", async () => {
const result = await call(
router.parts.getParts,
{},
- { context: ctx({ authKind: "oauth" }) }
+ { context: ctx({ authKind: "session" }) }
);
expect(result).toEqual({ data: "ok" });
});
diff --git a/apps/erp/app/services/oauth.server.test.ts b/apps/erp/app/services/oauth.server.test.ts
new file mode 100644
index 0000000000..7cd5da34be
--- /dev/null
+++ b/apps/erp/app/services/oauth.server.test.ts
@@ -0,0 +1,135 @@
+// 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 { describe, expect, it } from "vitest";
+import {
+ canAuthorizeForCompany,
+ isAllowedRedirectUri,
+ isRefreshTokenIdle,
+ isRegisteredRedirectUri,
+ supportedScope
+} from "./oauth.server";
+
+describe("isAllowedRedirectUri", () => {
+ it.each([
+ "https://claude.ai/api/mcp/auth_callback",
+ "http://localhost:33418/callback",
+ "http://127.0.0.1:6274/oauth/callback",
+ "http://[::1]:8080/cb",
+ "cursor://anysphere.cursor-retrieval/oauth/callback",
+ "com.example.app:/oauth2redirect"
+ ])("accepts %s", (uri) => {
+ expect(isAllowedRedirectUri(uri)).toBe(true);
+ });
+
+ it.each([
+ "http://evil.example/callback",
+ "http://localhost.evil.example/callback",
+ "https://evil.example/cb#fragment",
+ "https://user:[email protected]/cb",
+ "javascript:alert(1)",
+ "data:text/html,hi",
+ "file:///etc/passwd",
+ "ws://evil.example/cb",
+ "myapp:callback",
+ "not a url"
+ ])("refuses %s", (uri) => {
+ expect(isAllowedRedirectUri(uri)).toBe(false);
+ });
+});
+
+describe("isRegisteredRedirectUri", () => {
+ const registered = [
+ "https://claude.ai/api/mcp/auth_callback",
+ // Stored before /register checked redirect URIs.
+ "http://evil.example/cb"
+ ];
+
+ it("accepts a registered, allowed URI", () => {
+ expect(
+ isRegisteredRedirectUri(
+ registered,
+ "https://claude.ai/api/mcp/auth_callback"
+ )
+ ).toBe(true);
+ });
+
+ it("refuses a URI the client did not register", () => {
+ expect(isRegisteredRedirectUri(registered, "https://claude.ai/other")).toBe(
+ false
+ );
+ expect(isRegisteredRedirectUri(registered, null)).toBe(false);
+ });
+
+ it("refuses a registered URI the rules no longer allow", () => {
+ expect(isRegisteredRedirectUri(registered, "http://evil.example/cb")).toBe(
+ false
+ );
+ });
+});
+
+describe("isRefreshTokenIdle", () => {
+ const day = 24 * 3600 * 1000;
+ const now = Date.parse("2026-10-12T12:00:00Z");
+ // `expiresAt` is an hour after the last refresh.
+ const lastRefreshed = (daysAgo: number) =>
+ new Date(now - daysAgo * day + 3600 * 1000).toISOString();
+
+ it("keeps a token refreshed within the last 30 days", () => {
+ expect(isRefreshTokenIdle(lastRefreshed(0), now)).toBe(false);
+ expect(isRefreshTokenIdle(lastRefreshed(29), now)).toBe(false);
+ });
+
+ it("retires a token unused for more than 30 days", () => {
+ expect(isRefreshTokenIdle(lastRefreshed(31), now)).toBe(true);
+ });
+});
+
+describe("supportedScope", () => {
+ it("keeps only the scopes the server supports", () => {
+ expect(supportedScope("mcp:tools admin:all")).toBe("mcp:tools");
+ expect(supportedScope("mcp:tools mcp:tools")).toBe("mcp:tools");
+ });
+
+ it("returns null when nothing supported was requested", () => {
+ expect(supportedScope("admin:all")).toBeNull();
+ expect(supportedScope("")).toBeNull();
+ expect(supportedScope(null)).toBeNull();
+ });
+});
+
+describe("canAuthorizeForCompany", () => {
+ const settingsAdminIn = (...companyIds: string[]) => ({
+ settings: { view: companyIds, create: [], update: companyIds, delete: [] }
+ });
+
+ it("allows an employee holding settings_update in the selected company", () => {
+ expect(
+ canAuthorizeForCompany(
+ { companyId: "c1", role: "employee" },
+ settingsAdminIn("c1")
+ )
+ ).toBe(true);
+ });
+
+ // The session's active company is not the token's company: an admin of one
+ // company could otherwise mint a connector for another where they are not.
+ it("refuses when settings_update is held only in another company", () => {
+ expect(
+ canAuthorizeForCompany(
+ { companyId: "c2", role: "employee" },
+ settingsAdminIn("c1")
+ )
+ ).toBe(false);
+ });
+
+ it("refuses a customer or supplier portal account", () => {
+ expect(
+ canAuthorizeForCompany(
+ { companyId: "c1", role: "customer" },
+ settingsAdminIn("c1")
+ )
+ ).toBe(false);
+ });
+});
diff --git a/apps/erp/app/services/oauth.server.ts b/apps/erp/app/services/oauth.server.ts
new file mode 100644
index 0000000000..df42ee3a8a
--- /dev/null
+++ b/apps/erp/app/services/oauth.server.ts
@@ -0,0 +1,100 @@
+// 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.
+
+// OAuth 2.0 authorization-server rules shared by `/register` and `/authorize`.
+
+import type { Permission } from "@carbon/auth";
+
+// The only scope the MCP resource advertises (`/.well-known/oauth-protected-resource`).
+// A token carries no permissions of its own: every MCP call is gated on the
+// authorizing user's live permissions in the token's company.
+const SUPPORTED_SCOPES = new Set(["mcp:tools"]);
+
+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
+const FORBIDDEN_SCHEMES = new Set([
+ "javascript:",
+ "data:",
+ "vbscript:",
+ "file:",
+ "blob:",
+ "about:",
+ "ftp:",
+ "ws:",
+ "wss:"
+]);
+
+/**
+ * A redirect URI a client may register (RFC 8252 / OAuth 2.1): https anywhere,
+ * http only to a loopback address (a native client's local listener), or a
+ * private-use scheme (`cursor://…`). Never a fragment, and never a scheme a
+ * browser executes or reads locally.
+ */
+export function isAllowedRedirectUri(raw: string): boolean {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return false;
+ }
+ if (url.hash || raw.includes("#")) return false;
+ if (url.username || url.password) return false;
+ if (FORBIDDEN_SCHEMES.has(url.protocol)) return false;
+ if (url.protocol === "https:") return true;
+ if (url.protocol === "http:") return LOOPBACK_HOSTS.has(url.hostname);
+ // A private-use scheme is reverse-DNS by convention (`com.example.app:`);
+ // require at least a dot or a host so `foo:bar` is not accepted.
+ return url.host !== "" || url.protocol.includes(".");
+}
+
+/**
+ * Whether `redirectUri` may receive a code for a client: registered by it, and
+ * still allowed today. The second test covers clients registered before
+ * `isAllowedRedirectUri` existed, whose stored URIs were never checked.
+ */
+export function isRegisteredRedirectUri(
+ registered: readonly string[],
+ redirectUri: string | null
+): redirectUri is string {
+ return (
+ redirectUri !== null &&
+ registered.includes(redirectUri) &&
+ isAllowedRedirectUri(redirectUri)
+ );
+}
+
+/** The requested scopes this server supports; unknown ones are dropped, as
+ * RFC 7591 lets a server do. */
+export function supportedScope(scope: string | null | undefined) {
+ const granted = (scope ?? "")
+ .split(/\s+/)
+ .filter((s) => SUPPORTED_SCOPES.has(s));
+ return granted.length > 0 ? [...new Set(granted)].join(" ") : null;
+}
+
+/**
+ * Whether a user may authorize a connector for `companyId`: an employee there
+ * holding `settings_update` in THAT company. The token acts in the company it
+ * names, so the check cannot be the session's active company.
+ */
+export function canAuthorizeForCompany(
+ membership: { companyId: string; role: string },
+ permissions: Record<string, Permission>
+): boolean {
+ return (
+ membership.role === "employee" &&
+ (permissions.settings?.update.includes(membership.companyId) ?? false)
+ );
+}
+
+export const ACCESS_TOKEN_TTL_MS = 3600 * 1000;
+// A refresh token not used for this long is dead. Every refresh pushes
+// `expiresAt` an hour out, so `expiresAt` + this is the idle deadline — no
+// separate column. A connector in use refreshes hourly and never meets it.
+const REFRESH_TOKEN_IDLE_MS = 30 * 24 * 3600 * 1000;
+
+/** Whether a refresh token whose access token expires at `expiresAt` has sat
+ * unused past the idle limit at `nowMs`. */
+export function isRefreshTokenIdle(expiresAt: string, nowMs: number): boolean {
+ return new Date(expiresAt).getTime() + REFRESH_TOKEN_IDLE_MS < nowMs;
+}
diff --git a/apps/erp/test/mcp-tool-permissions.test.ts b/apps/erp/test/mcp-tool-permissions.test.ts
index 1b49b54563..d53280cf0e 100644
--- a/apps/erp/test/mcp-tool-permissions.test.ts
+++ b/apps/erp/test/mcp-tool-permissions.test.ts
@@ -23,24 +23,61 @@ const allTools = metadata.tools as Tool[];
// `@mcp permission` on the function — a route-verified exception that wins over
// the verb. Pinned exactly below and excluded from the verb-based assertions.
-// The API-key WRITES (upsert/delete) moved to @carbon/ee/api-keys.server behind
-// requireEntitlement, so they are no longer MCP tools — only the read
-// (getApiKeys) remains and keeps the override.
-const OVERRIDDEN = new Set(["settings_getApiKeys"]);
+// Each must match the permission the ERP route that does the same thing
+// requires: an OAuth connector or API key gated more loosely than the screen
+// can do what the screen forbids — and a service handed `db` writes past RLS,
+// so this gate is the only one.
+const OVERRIDES: Record<string, Tool["permission"]> = {
+ // API-key management. The writes (upsert/delete) moved to
+ // @carbon/ee/api-keys.server behind requireEntitlement and are no longer
+ // tools; only the read remains.
+ settings_getApiKeys: { module: "users", actions: ["update"] },
+ // Writes a GL journal: the Reconcile screen requires accounting_create.
+ inventory_createInventoryReconciliationJournal: {
+ module: "accounting",
+ actions: ["create"]
+ },
+ // Bank accounts: the table's RLS and every bank-account screen are accounting.
+ purchasing_getSupplierBankAccounts: { module: "accounting", actions: ["view"] },
+ purchasing_upsertSupplierBankAccount: {
+ module: "accounting",
+ actions: ["create", "update"]
+ },
+ purchasing_deleteSupplierBankAccount: {
+ module: "accounting",
+ actions: ["delete"]
+ },
+ sales_getCustomerBankAccounts: { module: "accounting", actions: ["view"] },
+ sales_upsertCustomerBankAccount: {
+ module: "accounting",
+ actions: ["create", "update"]
+ },
+ sales_deleteCustomerBankAccount: {
+ module: "accounting",
+ actions: ["delete"]
+ },
+ // Issue Credit writes a memo: its route requires invoicing_create.
+ purchasing_createPurchaseReturnOrderCredit: {
+ module: "invoicing",
+ actions: ["create"]
+ },
+ sales_createSalesReturnOrderCredit: {
+ module: "invoicing",
+ actions: ["create"]
+ }
+};
-const tools = allTools.filter((t) => !OVERRIDDEN.has(t.name));
+const tools = allTools.filter((t) => !(t.name in OVERRIDES));
describe("permission overrides", () => {
- it("API-key management gates on users_update, matching its ERP routes", () => {
- for (const name of OVERRIDDEN) {
+ it.each(Object.entries(OVERRIDES))(
+ "%s gates on the permission its ERP route requires",
+ (name, permission) => {
const t = allTools.find((t) => t.name === name);
expect(t, name).toBeDefined();
- expect(t?.permission, name).toEqual({
- module: "users",
- actions: ["update"]
- });
+ expect(t?.permission, name).toEqual(permission);
}
- });
+ );
});
describe("permission module mapping", () => {