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.

feat(auth): apply the self-signup email blocklist to Google/Outlook OAuth (#1665)

Brad Barbin4c7d7c20b46e
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 49ed07ac6d..60080f375a 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1802,3 +1802,13 @@ full-screen ERP route.
**Rule:** A migration that renames or drops any tenant-scoped table needs, in the same commit: (1) a `TABLE_RENAMES` entry (`packages/jobs/src/backups/renames.ts` — new name, or `null` if the feature died), (2) a default (or nullability) on any NEW NOT-NULL column of the rename target so old backup rows can load, and (3) a regenerated `manifests/schema.json`, which requires running `pnpm db:migrate` + `pnpm db:check:backups` against a live local DB. If the DB isn't running, say so — a skipped hook is not a passed check.
**Applies to:** `packages/database/supabase/migrations/**` table renames/drops, `packages/jobs/src/backups/renames.ts`, `packages/jobs/manifests/schema.json`, `.claude/rules/workflow-database-migration.md` step 3b.
+
+## OAuth signup bypasses app-level email gates — GoTrue provisions before your code runs
+
+**Context:** The free/disposable-domain self-signup blocklist (#1661) was enforced only on the email/password path (`login.tsx` unknown-user branch, `verify.tsx` before `createEmailAuthAccount`). "Sign in with Google" / "Sign in with Outlook" (`signInWithOAuth`) let a gmail/outlook address self-sign-up anyway.
+
+**Problem:** For OAuth there is no app-code seam before account creation. GoTrue creates the `auth.users` row during the IdP handshake and the `create_public_user` trigger fires inside that same transaction — all before the app's `/callback` action runs. So an email-path-only check has an OAuth-shaped hole, and the callback is the *first* point app code can react. The tempting "let it create, then delete it" teardown is a smell; the truly-earlier options (a GoTrue `before-user-created` hook, `GOTRUE_DISABLE_SIGNUP=true`, or a trigger `RAISE`) each cost more than they save (infra + Cloud config, or breaking existing-user first-time OAuth login, or a DB-resident blocklist + no edition signal + a raw error instead of a message).
+
+**Rule:** Any signup/identity gate must cover OAuth, not just the email path, and OAuth is enforced in the auth callback's non-SSO branch (both ERP and MES). Gate on a GENUINE self-signup only — no company membership AND no pending invite — so existing members and invited contractors pass. Prefer *not minting a session* over deleting the account: a membership-less `user` row can access nothing and is reused by `createEmployeeAccount` if the address is later invited, so no teardown is needed and the email stays invitable. Keep the check + domain list in one shared home (`@carbon/auth/self-signup.server`) so every entry point (ERP login/verify/callback + MES callback) shares one copy.
+
+**Applies to:** `apps/{erp,mes}/app/routes/_public+/callback.tsx` (non-SSO branch), `packages/auth/src/services/self-signup.server.ts`, and any future email/domain restriction — check the OAuth callback, not only the email/password flow.
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index e7277cddab..0f3be3b0d8 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -42,6 +42,19 @@ Magic link is the primary flow. The action rate-limits by IP (Upstash via `@carb
- Unknown user (non-Enterprise) → `sendVerificationCode`, redirect to `/verify` (email
verification-code signup). Enterprise edition rejects unknown users.
+**Self-signup blocklist (Cloud edition only)** — `isSelfSignupBlockedForEmail` /
+`SELF_SIGNUP_BLOCKED_MESSAGE` in `@carbon/auth/self-signup.server` (the domain list is
+the bundled `self-signup-blocked-domains.txt`, loaded via `?raw`). A brand-new
+self-signup on a free/disposable email domain is refused. The email path checks
+before the account exists — `login.tsx` (unknown-user branch) and `verify.tsx`
+(before `createEmailAuthAccount`). OAuth (Google/Azure) has **no** pre-create seam:
+GoTrue and the `create_public_user` trigger provision the user during the handshake,
+so both apps' `callback.tsx` refuse a blocked-domain **self-signup** (no company
+membership AND no pending `invite`) in the non-SSO branch and decline to mint a
+session — the inert, membership-less account is left as-is (a later legitimate invite
+reuses the row via `createEmployeeAccount`), so there is no teardown. Existing members
+and invited contractors are never affected. No-op outside Cloud edition.
+
Other methods on the login page: Google + Azure OAuth (`signInWithOAuth`, redirect to
`/callback`), Passkey/WebAuthn (`@simplewebauthn`, `/api/passkey/authenticate/*`,
backed by `passkey.server.ts`), and — Enterprise edition with `sso` in
diff --git a/apps/erp/app/routes/_public+/callback.tsx b/apps/erp/app/routes/_public+/callback.tsx
index d625e5d7e4..15fc7d822e 100644
--- a/apps/erp/app/routes/_public+/callback.tsx
+++ b/apps/erp/app/routes/_public+/callback.tsx
@@ -10,6 +10,10 @@ import { refreshAccessToken } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { getCompanyId, setCompanyId } from "@carbon/auth/company.server";
import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
+import {
+ isSelfSignupBlockedForEmail,
+ SELF_SIGNUP_BLOCKED_MESSAGE
+} from "@carbon/auth/self-signup.server";
import {
destroyAuthSession,
flash,
@@ -341,6 +345,43 @@ export async function action({ request }: ActionFunctionArgs) {
const user = await getUserByEmail(authSession.email);
if (user?.data) {
+ // Self-signup blocklist (Cloud only). The email/password path refuses a
+ // free/disposable domain in login.tsx and verify.tsx BEFORE the account is
+ // created; OAuth (Google/Azure) has no such seam — GoTrue creates the auth
+ // user and the `create_public_user` trigger fires before this action runs —
+ // so the callback is where we refuse it. Only a GENUINE self-signup is
+ // refused: a user who already belongs to a company (`pickable`), or who is
+ // holding a pending invite, is never a self-signup, so an existing gmail
+ // employee or an invited gmail contractor is unaffected. We simply decline
+ // to mint a session and leave the account: with no company it can access
+ // nothing, and a later legitimate invite reuses the same row
+ // (createEmployeeAccount), so there is nothing to tear down.
+ if (
+ pickable.length === 0 &&
+ isSelfSignupBlockedForEmail(authSession.email)
+ ) {
+ // ilike for the case fold only — escape LIKE metacharacters so %/_ in an
+ // address can never act as wildcards and match someone else's invite.
+ const invitePattern = authSession.email.replace(
+ /[\\%_]/g,
+ (match) => `\\${match}`
+ );
+ const pendingInvite = await serviceRole
+ .from("invite")
+ .select("id")
+ .ilike("email", invitePattern)
+ .is("acceptedAt", null)
+ .is("revokedAt", null)
+ .limit(1);
+
+ if (!pendingInvite.data?.length) {
+ return redirect(
+ path.to.root,
+ await flash(request, error(null, SELF_SIGNUP_BLOCKED_MESSAGE))
+ );
+ }
+ }
+
// Require-SSO gate: this is the non-SSO path (magic link, Google/Azure
// OAuth, magic links minted elsewhere) — a covered + enforced domain may
// only authenticate via SSO, so refuse before any session state is minted.
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index 885ddf6e86..c2ebdbcbb8 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -18,6 +18,10 @@ import {
verifyLoginCaptcha
} from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import {
+ isSelfSignupBlockedForEmail,
+ SELF_SIGNUP_BLOCKED_MESSAGE
+} from "@carbon/auth/self-signup.server";
import {
clearAuthCookies,
flash,
@@ -62,10 +66,6 @@ import {
useLoaderData,
useSearchParams
} from "react-router";
-import {
- isSelfSignupBlockedForEmail,
- SELF_SIGNUP_BLOCKED_MESSAGE
-} from "~/modules/shared/self-signup-blocklist.server";
import type { Result } from "~/types";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsx
index f69c48c3e2..60cd34a372 100644
--- a/apps/erp/app/routes/_public+/verify.tsx
+++ b/apps/erp/app/routes/_public+/verify.tsx
@@ -4,6 +4,10 @@ import {
createEmailAuthAccount,
signInWithEmail
} from "@carbon/auth/auth.server";
+import {
+ isSelfSignupBlockedForEmail,
+ SELF_SIGNUP_BLOCKED_MESSAGE
+} from "@carbon/auth/self-signup.server";
import {
flash,
getAuthSession,
@@ -36,10 +40,6 @@ import {
} from "react-router";
import { z } from "zod";
-import {
- isSelfSignupBlockedForEmail,
- SELF_SIGNUP_BLOCKED_MESSAGE
-} from "~/modules/shared/self-signup-blocklist.server";
import type { Result } from "~/types";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/_public+/callback.tsx b/apps/mes/app/routes/_public+/callback.tsx
index f739128cfd..820399c853 100644
--- a/apps/mes/app/routes/_public+/callback.tsx
+++ b/apps/mes/app/routes/_public+/callback.tsx
@@ -8,6 +8,10 @@ import { refreshAccessToken } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { setCompanyId } from "@carbon/auth/company.server";
import { userHasVerifiedTotpFactor } from "@carbon/auth/mfa.server";
+import {
+ isSelfSignupBlockedForEmail,
+ SELF_SIGNUP_BLOCKED_MESSAGE
+} from "@carbon/auth/self-signup.server";
import {
destroyAuthSession,
flash,
@@ -175,6 +179,40 @@ export async function action({ request }: ActionFunctionArgs) {
const user = await getUserByEmail(authSession.email);
if (user?.data) {
+ // Self-signup blocklist (Cloud only). OAuth (Google/Azure) has no pre-create
+ // seam — GoTrue creates the auth user and the `create_public_user` trigger
+ // fires before this action runs — so the callback is where we refuse it,
+ // mirroring the ERP callback. Only a GENUINE self-signup is refused: a user
+ // who already belongs to a company, or who holds a pending invite, is never
+ // a self-signup. We simply decline to mint a session and leave the inert,
+ // membership-less account; there is nothing to tear down.
+ const memberships = companies.data ?? [];
+ if (
+ memberships.length === 0 &&
+ isSelfSignupBlockedForEmail(authSession.email)
+ ) {
+ // ilike for the case fold only — escape LIKE metacharacters so %/_ in an
+ // address can never act as wildcards and match someone else's invite.
+ const invitePattern = authSession.email.replace(
+ /[\\%_]/g,
+ (match) => `\\${match}`
+ );
+ const pendingInvite = await serviceRole
+ .from("invite")
+ .select("id")
+ .ilike("email", invitePattern)
+ .is("acceptedAt", null)
+ .is("revokedAt", null)
+ .limit(1);
+
+ if (!pendingInvite.data?.length) {
+ return redirect(
+ path.to.root,
+ await flash(request, error(null, SELF_SIGNUP_BLOCKED_MESSAGE))
+ );
+ }
+ }
+
// Require-SSO gate: this is the non-SSO path (magic link, Google/Azure
// OAuth, magic links minted elsewhere) — a covered + enforced domain may
// only authenticate via SSO, so refuse before any session state is minted.
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 26e7e193d1..ddc07a5247 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -41,6 +41,7 @@ pnpm --filter @carbon/auth test
| `./company.server` | Company switching, `updateCompanySession` |
| `./users.server` | `getUserClaims`, deactivation flows, cache invalidation |
| `./passkey.server` | WebAuthn/passkey registration and authentication |
+| `./self-signup.server` | Cloud self-signup blocklist: `isSelfSignupBlockedForEmail`, `SELF_SIGNUP_BLOCKED_MESSAGE` (free/disposable email domains; used by ERP login/verify/callback + MES callback) |
| `./middleware/flash.server` | Flash message middleware |
SAML SSO lives in `@carbon/ee/sso.server` (Enterprise-gated), NOT here — auth
diff --git a/packages/auth/package.json b/packages/auth/package.json
index f1001a6e44..a310c167f2 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -19,6 +19,7 @@
"./company.server": "./src/services/company.server.ts",
"./mfa.server": "./src/services/mfa.server.ts",
"./session.server": "./src/services/session.server.ts",
+ "./self-signup.server": "./src/services/self-signup.server.ts",
"./users.server": "./src/services/users.server.ts",
"./passkey.server": "./src/services/passkey.server.ts",
"./verification.server": "./src/services/verification.server.ts",
diff --git a/packages/auth/src/raw.d.ts b/packages/auth/src/raw.d.ts
new file mode 100644
index 0000000000..df22351f8e
--- /dev/null
+++ b/packages/auth/src/raw.d.ts
@@ -0,0 +1,7 @@
+// `?raw` text imports are resolved by the consuming app's Vite build (ERP / MES).
+// This package is typechecked with tsgo, which doesn't know Vite's `?raw` suffix,
+// so declare the module shape here. Used by `services/self-signup.server.ts`.
+declare module "*?raw" {
+ const content: string;
+ export default content;
+}
diff --git a/apps/erp/app/modules/shared/self-signup-blocked-domains.txt b/packages/auth/src/services/self-signup-blocked-domains.txt
similarity index 99%
rename from apps/erp/app/modules/shared/self-signup-blocked-domains.txt
rename to packages/auth/src/services/self-signup-blocked-domains.txt
index fd907cff84..a810553ca3 100644
--- a/apps/erp/app/modules/shared/self-signup-blocked-domains.txt
+++ b/packages/auth/src/services/self-signup-blocked-domains.txt
@@ -2,7 +2,7 @@
#
# One domain per line (case-insensitive). Blank lines and lines starting with
# "#" are ignored. A new-user signup whose email domain matches an entry here is
-# refused in the Cloud edition only (see self-signup-blocklist.server.ts).
+# refused in the Cloud edition only (see self-signup.server.ts).
#
# This list is edited by hand and shipped with the app — add or remove a domain
# and deploy. It holds consumer/free webmail and disposable/temp-mail providers;
diff --git a/apps/erp/app/modules/shared/self-signup-blocklist.server.ts b/packages/auth/src/services/self-signup.server.ts
similarity index 63%
rename from apps/erp/app/modules/shared/self-signup-blocklist.server.ts
rename to packages/auth/src/services/self-signup.server.ts
index abe8b86409..5718b0773a 100644
--- a/apps/erp/app/modules/shared/self-signup-blocklist.server.ts
+++ b/packages/auth/src/services/self-signup.server.ts
@@ -1,9 +1,10 @@
import { CarbonEdition } from "@carbon/auth";
import { Edition } from "@carbon/utils";
-// The list ships with the app (bundled via `?raw`, same as the MCP setup prompt),
-// so editing `self-signup-blocked-domains.txt` and deploying is how it's
-// maintained. One domain per line; blank lines and `#` comments are ignored.
+// The list ships with this package and is bundled into the consuming app (ERP /
+// MES) by its Vite build via `?raw`, so editing `self-signup-blocked-domains.txt`
+// and deploying is how it's maintained. One domain per line; blank lines and `#`
+// comments are ignored.
import blockedDomainsRaw from "./self-signup-blocked-domains.txt?raw";
const blockedDomains = new Set(
@@ -21,8 +22,12 @@ export const SELF_SIGNUP_BLOCKED_MESSAGE =
* Whether a brand-new self-signup should be refused for this email. Only the
* Cloud edition enforces the blocklist — self-hosted/enterprise installs manage
* their own signup gating (edition check in login.tsx, `GOTRUE_DISABLE_SIGNUP`).
- * Existing users are unaffected: the login action only reaches this on the
- * unknown-user signup branch.
+ *
+ * Callers gate on "brand-new" themselves so existing users are unaffected:
+ * login.tsx/verify.tsx only reach this on the unknown-user signup branch, and
+ * the OAuth callback additionally requires no company membership and no pending
+ * invite before blocking (an existing gmail employee or an invited contractor
+ * is not a self-signup).
*/
export function isSelfSignupBlockedForEmail(email: string): boolean {
if (CarbonEdition !== Edition.Cloud) return false;