Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🔒️ Refuse Microsoft sign-ins whose verified email claim does not vouch for the address (#3230)
Luke Vella1879a2fbd748
diff --git a/apps/docs/self-hosting/single-sign-on.mdx b/apps/docs/self-hosting/single-sign-on.mdxindex bea0d75f1..79085661f 100644--- a/apps/docs/self-hosting/single-sign-on.mdx+++ b/apps/docs/self-hosting/single-sign-on.mdx@@ -44,6 +44,17 @@ After creating the application, set the redirect URI to:```https://<YOUR_DOMAIN>/api/auth/callback/microsoft-entra-id```++On a multi-tenant endpoint (`MICROSOFT_TENANT_ID` set to `common`, `organizations` or `consumers`) any tenant can assert any email address, so Rallly needs Microsoft to confirm the address before it creates an account from it. Microsoft does not include that information unless the app registration asks for it. While the claims are missing, Rallly still creates the account and logs a warning at sign-in; a later release will refuse these sign-ins. Add the `verified_primary_email` and `verified_secondary_email` optional claims to the ID token: in the app registration open **Manifest** and add these two entries to the `optionalClaims.idToken` array, keeping any claims already there:++```json+{ "name": "verified_primary_email", "source": null, "essential": false, "additionalProperties": [] },+{ "name": "verified_secondary_email", "source": null, "essential": false, "additionalProperties": [] }+```++If `optionalClaims` is `null`, replace it with `{ "idToken": [ ...the two entries... ] }`.++Once the claims are present, a Microsoft sign-in whose address is not among the verified ones fails with "Your email address is not verified". Existing users are not affected. Single-tenant registrations do not need this.</Accordion><ParamField path="MICROSOFT_TENANT_ID">diff --git a/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx b/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsxindex 0ac70068a..f971194d9 100644--- a/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx@@ -6,8 +6,12 @@ export function AuthErrors() {const { t } = useTranslation();const searchParams = useSearchParams();const error = searchParams?.get("error");+ if (!error) {+ return null;+ }switch (error) {case "OAuthAccountNotLinked":+ case "account_not_linked":return (<p className="text-destructive text-sm">{t("accountNotLinkedDescription", {@@ -17,6 +21,7 @@ export function AuthErrors() {</p>);case "EmailNotVerified":+ case "email_not_verified":return (<p className="text-destructive text-sm">{t("authErrorsEmailNotVerified", {@@ -52,7 +57,9 @@ export function AuthErrors() {})}</p>);- case "OAuthSignInFailed":+ // Better-Auth appends its own code to errorCallbackURL; anything not+ // mapped above still deserves a message rather than a silent login page.+ default:return (<p className="text-destructive text-sm">{t("authErrorsOAuthSignInFailed", {@@ -61,7 +68,5 @@ export function AuthErrors() {})}</p>);- default:- return null;}}diff --git a/apps/web/src/app/[locale]/(auth)/login/components/oidc-auto-sign-in.tsx b/apps/web/src/app/[locale]/(auth)/login/components/oidc-auto-sign-in.tsxindex b82e1173e..1536765cd 100644--- a/apps/web/src/app/[locale]/(auth)/login/components/oidc-auto-sign-in.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/components/oidc-auto-sign-in.tsx@@ -15,7 +15,7 @@ export function OIDCAutoSignIn() {authClient.signIn.oauth2({providerId: "oidc",callbackURL: validateRedirectUrl(redirectTo) || "/",- errorCallbackURL: "/login?error=OAuthSignInFailed",+ errorCallbackURL: "/login",});});diff --git a/apps/web/src/features/auth/components/login-with-oidc.tsx b/apps/web/src/features/auth/components/login-with-oidc.tsxindex af462f6b7..45d7f3780 100644--- a/apps/web/src/features/auth/components/login-with-oidc.tsx+++ b/apps/web/src/features/auth/components/login-with-oidc.tsx@@ -17,7 +17,7 @@ export function LoginWithOIDC({authClient.signIn.oauth2({providerId: "oidc",callbackURL: validateRedirectUrl(redirectTo) || "/",- errorCallbackURL: "/login?error=OAuthSignInFailed",+ errorCallbackURL: "/login",});}}className="w-full"diff --git a/apps/web/src/features/auth/components/sso-provider.tsx b/apps/web/src/features/auth/components/sso-provider.tsxindex 101f77dd5..57985c85a 100644--- a/apps/web/src/features/auth/components/sso-provider.tsx+++ b/apps/web/src/features/auth/components/sso-provider.tsx@@ -39,6 +39,7 @@ export function SSOProvider({authClient.signIn.social({provider: providerId,callbackURL: validateRedirectUrl(redirectTo) || "/",+ errorCallbackURL: "/login",});}}>diff --git a/apps/web/src/lib/auth-plugins/microsoft-email-claim.test.ts b/apps/web/src/lib/auth-plugins/microsoft-email-claim.test.tsnew file mode 100644index 000000000..595d4e4c5--- /dev/null+++ b/apps/web/src/lib/auth-plugins/microsoft-email-claim.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from "vitest";++import {+ readMicrosoftEmailClaim,+ rememberMicrosoftEmailClaim,+ takeMicrosoftEmailClaim,+} from "./microsoft-email-claim";++describe("readMicrosoftEmailClaim", () => {+ it("is absent when the registration emits no verification claim", () => {+ expect(readMicrosoftEmailClaim({ email: "[email protected]" })).toBe("absent");+ });++ it("is verified when the address is in the primary list", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ verified_primary_email: ["[email protected]"],+ }),+ ).toBe("verified");+ });++ it("matches exactly, as better-auth does when it sets emailVerified", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ verified_primary_email: ["[email protected]"],+ }),+ ).toBe("unverified");+ });++ it("is verified when the address is only in the secondary list", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ verified_primary_email: [],+ verified_secondary_email: ["[email protected]"],+ }),+ ).toBe("verified");+ });++ it("is unverified when the claim is present but does not carry the address", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ verified_primary_email: ["[email protected]"],+ }),+ ).toBe("unverified");+ });++ it("is unverified when the claim is present and empty", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ verified_primary_email: [],+ }),+ ).toBe("unverified");+ });++ it("prefers an explicit email_verified claim", () => {+ expect(+ readMicrosoftEmailClaim({+ email: "[email protected]",+ email_verified: false,+ verified_primary_email: ["[email protected]"],+ }),+ ).toBe("unverified");+ });+});++describe("claim registry", () => {+ it("hands the reading over once, case-insensitively", () => {+ rememberMicrosoftEmailClaim({ email: "[email protected]", claim: "absent" });+ expect(takeMicrosoftEmailClaim("[email protected]")).toBe("absent");+ expect(takeMicrosoftEmailClaim("[email protected]")).toBeUndefined();+ });+});diff --git a/apps/web/src/lib/auth-plugins/microsoft-email-claim.ts b/apps/web/src/lib/auth-plugins/microsoft-email-claim.tsnew file mode 100644index 000000000..85e155bb6--- /dev/null+++ b/apps/web/src/lib/auth-plugins/microsoft-email-claim.ts@@ -0,0 +1,63 @@+// Microsoft only vouches for an address when the app registration requests+// the verified email optional claims. Their absence means the registration is+// unconfigured, which is a different situation from Microsoft declining to+// vouch, and the two need different handling downstream.+//+// The claim is only visible where the ID token is decoded (the provider's+// profile mapping), while the decision is made in the user create hook, which+// sees the mapped user only. The registry carries the reading between the two+// within one sign-in; entries are consumed on read and expire quickly.++export type MicrosoftEmailClaim = "verified" | "unverified" | "absent";++export function readMicrosoftEmailClaim(profile: {+ email?: string | undefined;+ email_verified?: boolean | undefined;+ verified_primary_email?: string[] | undefined;+ verified_secondary_email?: string[] | undefined;+}): MicrosoftEmailClaim {+ if (typeof profile.email_verified === "boolean") {+ return profile.email_verified ? "verified" : "unverified";+ }+ const primary = profile.verified_primary_email;+ const secondary = profile.verified_secondary_email;+ if (!Array.isArray(primary) && !Array.isArray(secondary)) {+ return "absent";+ }+ // Exact match, the same comparison better-auth makes when it derives+ // emailVerified from these claims, so the two readings never disagree.+ const email = profile.email;+ const verified =+ !!email && [...(primary ?? []), ...(secondary ?? [])].includes(email);+ return verified ? "verified" : "unverified";+}++const TTL_MS = 60_000;++const pending = new Map<string, { claim: MicrosoftEmailClaim; at: number }>();++export function rememberMicrosoftEmailClaim({+ email,+ claim,+}: {+ email: string;+ claim: MicrosoftEmailClaim;+}) {+ const now = Date.now();+ for (const [key, entry] of pending) {+ if (now - entry.at > TTL_MS) {+ pending.delete(key);+ }+ }+ pending.set(email.toLowerCase(), { claim, at: now });+}++export function takeMicrosoftEmailClaim(email: string) {+ const key = email.toLowerCase();+ const entry = pending.get(key);+ pending.delete(key);+ if (!entry || Date.now() - entry.at > TTL_MS) {+ return undefined;+ }+ return entry.claim;+}diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex 6e65861f4..7804b075b 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -39,6 +39,11 @@ import {} from "@/lib/acquisition";import { SESSION_TTL_SECONDS } from "@/lib/auth-config";import { hostOnlyCookieCleanup } from "@/lib/auth-plugins/host-only-cookie-cleanup";+import {+ readMicrosoftEmailClaim,+ rememberMicrosoftEmailClaim,+ takeMicrosoftEmailClaim,+} from "@/lib/auth-plugins/microsoft-email-claim";import { redis } from "@/lib/kv";import {LOCALE_COOKIE_NAME,@@ -120,6 +125,23 @@ const conditionalPlugins: BetterAuthPlugin[] = [: []),];+const isMultiTenantMicrosoft = [+ "common",+ "organizations",+ "consumers",+].includes(env.MICROSOFT_TENANT_ID);++let microsoftClaimWarned = false;+function warnMicrosoftClaimMissing() {+ if (microsoftClaimWarned) {+ return;+ }+ microsoftClaimWarned = true;+ logger.warn(+ "Microsoft sign-in is creating accounts from unverified email addresses because the app registration does not emit the verified_primary_email claim. Add it before the next release, which will refuse these sign-ins: https://support.rallly.co/self-hosting/single-sign-on#microsoft",+ );+}+export const authLib = betterAuth({appName: env.APP_NAME,secret: env.SECRET_PASSWORD,@@ -236,6 +258,15 @@ export const authLib = betterAuth({clientId: env.MICROSOFT_CLIENT_ID,clientSecret: env.MICROSOFT_CLIENT_SECRET,redirectURI: absoluteUrl("/api/auth/callback/microsoft-entra-id"),+ mapProfileToUser: (profile) => {+ if (profile.email) {+ rememberMicrosoftEmailClaim({+ email: profile.email,+ claim: readMicrosoftEmailClaim(profile),+ });+ }+ return {};+ },}: undefined,},@@ -479,6 +510,41 @@ export const authLib = betterAuth({databaseHooks: {user: {create: {+ // On a multi-tenant Microsoft endpoint any tenant admin can put any+ // address on a user, so an unverified address must not become an+ // account: the mailbox owner's later OTP login would land in it with+ // the Microsoft link intact. Microsoft only vouches when the app+ // registration requests the verified email claims, so their absence+ // means an unconfigured registration rather than a refusal. That+ // case is allowed with a warning for now and becomes a rejection in+ // a later release. Single-tenant Microsoft is the instance's own+ // directory; OIDC likewise; Google always asserts email_verified.+ before: async (user, ctx) => {+ // The redirect callback names the provider in the route; the+ // ID-token variant of /sign-in/social names it in the body.+ const provider = ctx?.params?.id ?? ctx?.body?.provider;+ if (+ user.isAnonymous ||+ user.emailVerified ||+ provider !== "microsoft"+ ) {+ return;+ }+ // better-auth derives emailVerified from the same claims, so an+ // unverified user here means the claim was absent, declined to+ // vouch, or never recorded for this sign-in (fail closed).+ const claim = takeMicrosoftEmailClaim(user.email);+ if (claim === "absent") {+ if (isMultiTenantMicrosoft) {+ warnMicrosoftClaimMissing();+ }+ return;+ }+ throw new APIError("FORBIDDEN", {+ code: "EMAIL_NOT_VERIFIED",+ message: "email not verified",+ });+ },after: async (user, ctx) => {if (user.isAnonymous) {return;