Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Check a Microsoft account can host Teams meetings when it connects (#3400)
Luke Vellad7de7b8f1422
diff --git a/apps/docs/integrations/microsoft-teams.mdx b/apps/docs/integrations/microsoft-teams.mdxindex 0f31c9031..957432054 100644--- a/apps/docs/integrations/microsoft-teams.mdx+++ b/apps/docs/integrations/microsoft-teams.mdx@@ -36,6 +36,8 @@ The meeting is created on the Microsoft account you connected, so it follows you</Step></Steps>+When you connect, Rallly checks that the account can create Teams meetings by creating a test meeting and deleting it straight away. The test meeting does not appear in your calendar or in Teams. If Microsoft refuses it, Rallly does not connect the account and tells you why; see [Troubleshooting](#troubleshooting).+You can connect one Microsoft account for Microsoft Teams. To switch to a different account, disconnect the current one, then connect the new one.Connecting Microsoft Teams is separate from signing in to Rallly with Microsoft. You can sign in with any method and still connect Teams, and connecting Teams does not change how you sign in.@@ -74,7 +76,7 @@ When you finalize the poll and pick the winning time, Rallly:Rallly does not add the meeting to your Outlook calendar; the calendar invite Rallly sends covers it.-If the meeting cannot be created, for example because the Microsoft connection has expired or your account has no Teams license, the poll stays open and Rallly shows an error. Reconnect your account in Conferencing settings and finalize again.+If the meeting cannot be created, for example because the Microsoft connection has expired or your account no longer has a Teams license, the poll stays open and Rallly shows an error that says which it is. See [Troubleshooting](#troubleshooting).### Which account hosts the meeting@@ -86,12 +88,12 @@ When you connect, Rallly asks Microsoft for these permissions:| Permission | Why || --- | --- |-| Read and create your online meetings (`OnlineMeetings.ReadWrite`) | To create the Teams meeting when you finalize a poll. |+| Read and create your online meetings (`OnlineMeetings.ReadWrite`) | To create the Teams meeting when you finalize a poll, and to check once, when you connect, that your account can create meetings. || Sign you in and read your profile (`User.Read`) | To identify the connection and show which account is connected. || Maintain access to data you have given it access to (`offline_access`) | So Rallly can create meetings when you finalize a poll without asking you to sign in each time. || View your basic profile and email address (`openid`, `profile`, `email`) | Requested with the sign in to identify the account. Rallly does not store your name. |-Rallly uses `OnlineMeetings.ReadWrite` only to create a meeting when you finalize a poll. Rallly does not read your other meetings, chats, recordings, transcripts, files, contacts, calendar or email, and does not join or record meetings.+Rallly uses `OnlineMeetings.ReadWrite` only to create a meeting when you finalize a poll and to create and immediately delete one test meeting when you connect. Rallly does not read your other meetings, chats, recordings, transcripts, files, contacts, calendar or email, and does not join or record meetings.## Data Rallly stores@@ -131,9 +133,13 @@ If you do not see the option, your organization manages app permissions centrall**Microsoft does not accept your personal account.** Microsoft Teams meetings can only be created for work or school accounts. Connect the account your organization gave you.+**Rallly says the account can't create Teams meetings.** Microsoft refused the test meeting Rallly creates when you connect. The account has no Teams license, Teams has never been opened with it, or your organization's policies do not let it create meetings. Open [Teams](https://teams.microsoft.com) with that account: if Teams does not open, ask your IT administrator for a license that includes Teams. Once Teams opens, connect the account in Rallly again.+**"Microsoft Teams is not connected" when creating a poll.** Your Rallly account has no Microsoft Teams connection, or it was removed. Connect one in Conferencing settings and choose Microsoft Teams again.-**Finalizing fails with a video call error.** Your account may have no Teams license, you may never have used Teams with it, the connection may have expired after 90 days without use, or your password was changed or your administrator removed Rallly. Check that you can open Teams with that account, then disconnect and reconnect Microsoft Teams in Conferencing settings and finalize again. The poll is unchanged until finalizing succeeds.+**Finalizing fails because Microsoft Teams couldn't create the meeting.** The account could create meetings when you connected it and no longer can, usually because its Teams license was removed. Check that you can open Teams with that account, then finalize again. The poll is unchanged until finalizing succeeds.++**Finalizing fails because the account is not connected.** The connection expired after 90 days without use, your password was changed, or your administrator removed Rallly. Disconnect and reconnect Microsoft Teams in Conferencing settings and finalize again.**Participants wait in the lobby.** Who waits in the lobby follows your organization's Teams meeting policies. The host can admit people from the meeting, or change the meeting options in Teams.diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 4ee96c375..5a30fccb2 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -12,6 +12,7 @@"accountDeletionCancelled": "Your account is no longer scheduled for deletion","accountMenu": "Account menu","accountNotLinkedDescription": "A user with this email already exists. Please log in using the original method.",+ "actionErrorConferencingCannotHost": "Microsoft Teams couldn't create the meeting. Check that your Microsoft account has a Teams license and that you can open Teams with it, then try again.","actionErrorConferencingFailed": "We couldn't create the meeting link. Check your account in Conferencing settings and try again.","actionErrorConferencingNotConnected": "Your video call account is not connected. Connect it in Conferencing settings and try again.","actionErrorForbidden": "You are not allowed to perform this action",@@ -180,6 +181,8 @@"conferencingDisconnecting": "Disconnecting account…","conferencingNotConnected": "{provider} is not connected. Visit the <a>Conferencing settings</a> page to connect your account.","conferencingTeamsAdminConsentHint": "If your organization requires admin approval, send this link to your IT administrator.",+ "conferencingTeamsCannotHost": "This Microsoft account can't create Teams meetings",+ "conferencingTeamsCannotHostDescription": "It needs a Teams license, and Teams must have been opened with it at least once. Check with your IT administrator, then connect again.","configuredByEnvironmentVariable": "This setting has been configured by environment variable.","confirm": "Confirm","confirmSpaceName": "Please type the space name to confirm:",diff --git a/apps/web/src/app/api/integrations/[...connection]/route.ts b/apps/web/src/app/api/integrations/[...connection]/route.tsindex 90004ad08..8aa2413fe 100644--- a/apps/web/src/app/api/integrations/[...connection]/route.ts+++ b/apps/web/src/app/api/integrations/[...connection]/route.ts@@ -10,9 +10,11 @@ import {} from "@/features/conferencing/constants";import { createConferencingConnection } from "@/features/conferencing/mutations";import type { ConferencingProvider } from "@/features/conferencing/schema";+import { checkTeamsCanHostMeetings } from "@/features/conferencing/service";import { getMicrosoftTeamsAuthority } from "@/features/conferencing/utils";import { saveOAuthCredentials } from "@/features/credentials/mutations";import { getSession } from "@/lib/auth";+import { OAuthConnectionRefusedError } from "@/lib/oauth/errors";import { GoogleOAuthClient } from "@/lib/oauth/providers/google";import { MicrosoftOAuthClient } from "@/lib/oauth/providers/microsoft";import { ZoomOAuthClient } from "@/lib/oauth/providers/zoom";@@ -182,10 +184,20 @@ const { handler } = OAuthIntegration<Integration>({clientSecret: env.MICROSOFT_CLIENT_SECRET,callbackUrl,scopes: MICROSOFT_TEAMS_SCOPES,- onConnect: conferencingOnConnect({- integrationId,- displayName: "Microsoft Teams",- }),+ onConnect: async (params) => {+ // An account without a Teams license signs in fine and only+ // fails when a poll is finalized, so it is refused here instead.+ const check = await checkTeamsCanHostMeetings({+ accessToken: params.tokens.accessToken,+ });+ if (!check.ok && check.reason === "refused") {+ throw new OAuthConnectionRefusedError("cannot_host_meetings");+ }+ await conferencingOnConnect({+ integrationId,+ displayName: "Microsoft Teams",+ })(params);+ },});}default:diff --git a/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsxindex 0dbd6040a..c198f0dd0 100644--- a/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx+++ b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx@@ -38,6 +38,21 @@ export function ConferencingConnectionFlash() {"The app was not approved. People in your organization still can't connect it.",}),);+ } else if (flash.startsWith("error:cannot_host_meetings:")) {+ // Nothing the user can retry their way out of, so it stays until closed.+ toast.error(+ t("conferencingTeamsCannotHost", {+ defaultValue: "This Microsoft account can't create Teams meetings",+ }),+ {+ description: t("conferencingTeamsCannotHostDescription", {+ defaultValue:+ "It needs a Teams license, and Teams must have been opened with it at least once. Check with your IT administrator, then connect again.",+ }),+ duration: Number.POSITIVE_INFINITY,+ closeButton: true,+ },+ );} else if (flash.endsWith(":microsoft-teams")) {// A failure here is often the organization's consent policy, which// only an administrator can resolve, so the toast stays until closed.diff --git a/apps/web/src/features/conferencing/service.test.ts b/apps/web/src/features/conferencing/service.test.tsnew file mode 100644index 000000000..0b97b165a--- /dev/null+++ b/apps/web/src/features/conferencing/service.test.ts@@ -0,0 +1,132 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { checkTeamsCanHostMeetings } from "./service";++vi.mock("@/env", () => ({ env: {} }));++const meetingsUrl = "https://graph.microsoft.com/v1.0/me/onlineMeetings";++function respond(status: number, body?: unknown) {+ return new Response(body === undefined ? null : JSON.stringify(body), {+ status,+ });+}++function stubFetch(...outcomes: Array<Response | { rejects: unknown }>) {+ const fetchStub = vi.fn();+ for (const outcome of outcomes) {+ if ("rejects" in outcome) {+ fetchStub.mockRejectedValueOnce(outcome.rejects);+ } else {+ fetchStub.mockResolvedValueOnce(outcome);+ }+ }+ vi.stubGlobal("fetch", fetchStub);+ return fetchStub;+}++describe("checkTeamsCanHostMeetings", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("creates a test meeting and deletes it again", async () => {+ const fetchStub = stubFetch(+ respond(201, { id: "meeting/1" }),+ respond(204),+ );++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: true,+ });+ expect(fetchStub).toHaveBeenCalledTimes(2);+ expect(fetchStub.mock.calls[0]?.[0]).toBe(meetingsUrl);+ expect(fetchStub.mock.calls[0]?.[1]).toMatchObject({ method: "POST" });+ expect(fetchStub.mock.calls[1]?.[0]).toBe(`${meetingsUrl}/meeting%2F1`);+ expect(fetchStub.mock.calls[1]?.[1]).toMatchObject({ method: "DELETE" });+ });++ it("refuses an account Microsoft will not create a meeting for", async () => {+ const fetchStub = stubFetch(+ respond(400, { error: { code: "BadRequest" } }),+ );++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: false,+ reason: "refused",+ });+ expect(fetchStub).toHaveBeenCalledTimes(1);+ });++ it("still refuses when the refusal's body cannot be read", async () => {+ const refusal = respond(403);+ vi.spyOn(refusal, "text").mockRejectedValue(+ new DOMException("The operation timed out.", "TimeoutError"),+ );+ stubFetch(refusal);++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: false,+ reason: "refused",+ });+ });++ it("is inconclusive when Microsoft is unavailable or throttling", async () => {+ stubFetch(respond(503));+ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: false,+ reason: "inconclusive",+ });++ stubFetch(respond(429));+ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: false,+ reason: "inconclusive",+ });+ });++ it("is inconclusive when the request never completes", async () => {+ stubFetch({+ rejects: new DOMException("The operation timed out.", "TimeoutError"),+ });++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: false,+ reason: "inconclusive",+ });+ });++ it("bounds both requests with an abort signal", async () => {+ const fetchStub = stubFetch(respond(201, { id: "1" }), respond(204));++ await checkTeamsCanHostMeetings({ accessToken: "token" });++ expect(fetchStub.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal);+ expect(fetchStub.mock.calls[1]?.[1]?.signal).toBeInstanceOf(AbortSignal);+ });++ it("retries the delete once and still reports the account as able", async () => {+ const fetchStub = stubFetch(+ respond(201, { id: "1" }),+ respond(503),+ respond(204),+ );++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: true,+ });+ expect(fetchStub).toHaveBeenCalledTimes(3);+ });++ it("reports the account as able even when the delete keeps failing", async () => {+ const fetchStub = stubFetch(+ respond(201, { id: "1" }),+ { rejects: new Error("network") },+ respond(500),+ );++ expect(await checkTeamsCanHostMeetings({ accessToken: "token" })).toEqual({+ ok: true,+ });+ expect(fetchStub).toHaveBeenCalledTimes(3);+ });+});diff --git a/apps/web/src/features/conferencing/service.ts b/apps/web/src/features/conferencing/service.tsindex 39b2540d7..4d1e96fb2 100644--- a/apps/web/src/features/conferencing/service.ts+++ b/apps/web/src/features/conferencing/service.ts@@ -14,8 +14,10 @@ import { getConferencingConnectionForProvider } from "./data";import type { Conferencing, ConferencingProvider } from "./schema";import {getMicrosoftTeamsAuthority,+ isTeamsMeetingRefusal,meetSpaceResponseSchema,meetSpaceToConferencing,+ teamsMeetingProbeResponseSchema,teamsMeetingResponseSchema,teamsMeetingToConferencing,zoomMeetingResponseSchema,@@ -26,7 +28,24 @@ const logger = createLogger("conferencing/service");export type CreateConferencingMeetingResult =| { ok: true; conferencing: Conferencing }- | { ok: false; reason: "not_connected" | "provider_error" };+ | {+ ok: false;+ reason: "not_connected" | "cannot_host" | "provider_error";+ };++// Microsoft refused the request itself, which reconnecting does not fix: the+// account has no Teams license, never opened Teams, or a policy blocks it.+class TeamsMeetingRefusedError extends Error {+ status: number;+ constructor({ status, body }: { status: number; body: string }) {+ super(`Teams meeting creation refused with status ${status}: ${body}`);+ this.name = "TeamsMeetingRefusedError";+ this.status = status;+ }+}++const TEAMS_ONLINE_MEETINGS_URL =+ "https://graph.microsoft.com/v1.0/me/onlineMeetings";// Mints a meeting link for a scheduled time. The organizer's own account// hosts the meeting, so the link inherits their provider settings.@@ -98,6 +117,13 @@ export async function createConferencingMeeting({);return { ok: false, reason: "not_connected" };}+ if (error instanceof TeamsMeetingRefusedError) {+ logger.warn(+ { err: error, userId, provider, connectionId: connection.id },+ "Microsoft account cannot host Teams meetings",+ );+ return { ok: false, reason: "cannot_host" };+ }// `err` is the key pino's default serializer expands; `error` logs as {}.logger.error({ err: error, userId, provider, connectionId: connection.id },@@ -276,25 +302,27 @@ async function createTeamsMeeting({start: Date;end: Date;}): Promise<Conferencing> {- const res = await fetch(- "https://graph.microsoft.com/v1.0/me/onlineMeetings",- {- method: "POST",- headers: {- Authorization: `Bearer ${accessToken}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- subject: title,- startDateTime: start.toISOString(),- endDateTime: end.toISOString(),- }),+ const res = await fetch(TEAMS_ONLINE_MEETINGS_URL, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",},- );+ body: JSON.stringify({+ subject: title,+ startDateTime: start.toISOString(),+ endDateTime: end.toISOString(),+ }),+ });if (!res.ok) {+ // Read for the log only; the status decides which error this is.+ const body = await res.text().catch(() => "");+ if (isTeamsMeetingRefusal(res.status)) {+ throw new TeamsMeetingRefusedError({ status: res.status, body });+ }throw new Error(- `Teams meeting creation failed with status ${res.status}: ${await res.text()}`,+ `Teams meeting creation failed with status ${res.status}: ${body}`,);}@@ -303,6 +331,105 @@ async function createTeamsMeeting({);}+export type TeamsHostCheckResult =+ | { ok: true }+ | { ok: false; reason: "refused" | "inconclusive" };++// The check runs inside the OAuth callback, so a request Microsoft never+// answers must not hold the connection open.+const TEAMS_CHECK_CREATE_TIMEOUT_MS = 10_000;+const TEAMS_CHECK_DELETE_TIMEOUT_MS = 5_000;++// Proves at connect time that the account can host meetings, by creating one+// and deleting it again, so a missing Teams license surfaces while the user+// is looking at the connection rather than when they finalize a poll. Graph+// meetings are never written to a calendar, so the user sees nothing. Only a+// refusal blocks the connection; an outage, a timeout or a throttle must not.+export async function checkTeamsCanHostMeetings({+ accessToken,+}: {+ accessToken: string;+}): Promise<TeamsHostCheckResult> {+ const headers = {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ };++ let meetingId: string;+ try {+ const start = new Date(Date.now() + 60 * 60_000);+ const end = new Date(start.getTime() + 30 * 60_000);+ const res = await fetch(TEAMS_ONLINE_MEETINGS_URL, {+ method: "POST",+ headers,+ body: JSON.stringify({+ subject: "Rallly connection check",+ startDateTime: start.toISOString(),+ endDateTime: end.toISOString(),+ }),+ signal: AbortSignal.timeout(TEAMS_CHECK_CREATE_TIMEOUT_MS),+ });++ if (!res.ok) {+ // The status alone decides; the body is only read for the log, and a+ // read that fails must not turn a refusal into an inconclusive check.+ const refused = isTeamsMeetingRefusal(res.status);+ const body = await res.text().catch(() => undefined);+ logger.warn(+ { status: res.status, body, refused },+ "Teams connection check did not create a meeting",+ );+ return { ok: false, reason: refused ? "refused" : "inconclusive" };+ }++ meetingId = teamsMeetingProbeResponseSchema.parse(await res.json()).id;+ } catch (error) {+ logger.warn({ err: error }, "Teams connection check failed to run");+ return { ok: false, reason: "inconclusive" };+ }++ // The account has proven it can host. Whether the test meeting could be+ // removed is a separate matter and never changes that answer.+ await deleteTeamsCheckMeeting({ meetingId, headers });+ return { ok: true };+}++// Tried twice, since a failure here is usually transient. A meeting that+// stays behind is on no calendar and expires on Microsoft's side; its id is+// logged so it can be removed by hand.+async function deleteTeamsCheckMeeting({+ meetingId,+ headers,+}: {+ meetingId: string;+ headers: Record<string, string>;+}) {+ let failure: unknown;+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ const res = await fetch(+ `${TEAMS_ONLINE_MEETINGS_URL}/${encodeURIComponent(meetingId)}`,+ {+ method: "DELETE",+ headers,+ signal: AbortSignal.timeout(TEAMS_CHECK_DELETE_TIMEOUT_MS),+ },+ );+ // Already gone is as good as deleted.+ if (res.ok || res.status === 404) {+ return;+ }+ failure = new Error(`Delete answered with status ${res.status}`);+ } catch (error) {+ failure = error;+ }+ }+ logger.warn(+ { err: failure, meetingId },+ "Teams connection check meeting was left behind",+ );+}+async function createMeetSpace(credentials: OAuthCredentials,): Promise<Conferencing> {diff --git a/apps/web/src/features/conferencing/utils.test.ts b/apps/web/src/features/conferencing/utils.test.tsindex 825484dda..207a84fbd 100644--- a/apps/web/src/features/conferencing/utils.test.ts+++ b/apps/web/src/features/conferencing/utils.test.ts@@ -6,6 +6,7 @@ import {getConferencingUri,getMicrosoftTeamsAuthority,isEmailAllowlisted,+ isTeamsMeetingRefusal,meetSpaceResponseSchema,meetSpaceToConferencing,teamsMeetingResponseSchema,@@ -118,6 +119,26 @@ describe("teamsMeetingToConferencing", () => {});});+describe("isTeamsMeetingRefusal", () => {+ it("reads a client error as the account being unable to host", () => {+ expect(isTeamsMeetingRefusal(400)).toBe(true);+ expect(isTeamsMeetingRefusal(403)).toBe(true);+ expect(isTeamsMeetingRefusal(404)).toBe(true);+ });++ it("does not blame the account for a bad token, a timeout or throttling", () => {+ expect(isTeamsMeetingRefusal(401)).toBe(false);+ expect(isTeamsMeetingRefusal(408)).toBe(false);+ expect(isTeamsMeetingRefusal(429)).toBe(false);+ });++ it("does not blame the account for a Microsoft outage or a success", () => {+ expect(isTeamsMeetingRefusal(500)).toBe(false);+ expect(isTeamsMeetingRefusal(503)).toBe(false);+ expect(isTeamsMeetingRefusal(201)).toBe(false);+ });+});+describe("getMicrosoftTeamsAuthority", () => {it("keeps personal accounts out of a multitenant registration", () => {expect(getMicrosoftTeamsAuthority("common")).toBe("organizations");diff --git a/apps/web/src/features/conferencing/utils.ts b/apps/web/src/features/conferencing/utils.tsindex 7b544df31..ad723f435 100644--- a/apps/web/src/features/conferencing/utils.ts+++ b/apps/web/src/features/conferencing/utils.ts@@ -86,6 +86,25 @@ export function teamsMeetingToConferencing(};}+// The meeting Rallly creates and deletes to check an account at connect time.+export const teamsMeetingProbeResponseSchema = z.object({+ id: z.string().min(1),+});++// Graph answers a request the account is not entitled to make with a client+// error: no Teams license, Teams never opened, or a policy that blocks+// meetings. 401 (token), 408 (timeout) and 429 (throttling) say nothing about+// the account.+export function isTeamsMeetingRefusal(status: number) {+ return (+ status >= 400 &&+ status < 500 &&+ status !== 401 &&+ status !== 408 &&+ status !== 429+ );+}+// Graph's online meetings API serves work and school accounts only, so a// multitenant registration connects Teams through the `organizations`// authority, which keeps personal accounts from starting the flow. A singlediff --git a/apps/web/src/lib/errors/app-error.ts b/apps/web/src/lib/errors/app-error.tsindex d94e22e1b..958780b5b 100644--- a/apps/web/src/lib/errors/app-error.ts+++ b/apps/web/src/lib/errors/app-error.ts@@ -11,6 +11,7 @@ export type AppErrorCode =| "SETUP_REQUIRED"| "TOO_MANY_REQUESTS"| "CONFERENCING_NOT_CONNECTED"+ | "CONFERENCING_CANNOT_HOST"| "CONFERENCING_FAILED";export class AppError extends Error {diff --git a/apps/web/src/lib/oauth/errors.ts b/apps/web/src/lib/oauth/errors.tsnew file mode 100644index 000000000..6cef6d2e2--- /dev/null+++ b/apps/web/src/lib/oauth/errors.ts@@ -0,0 +1,11 @@+// Thrown from `onConnect` to refuse a connection for a reason the landing page+// can explain. The reason travels in the outcome flash, whose fields are+// colon separated, so it is limited to lowercase words and underscores.+export class OAuthConnectionRefusedError extends Error {+ reason: string;+ constructor(reason: string) {+ super(`OAuth connection refused: ${reason}`);+ this.name = "OAuthConnectionRefusedError";+ this.reason = /^[a-z_]+$/.test(reason) ? reason : "connection_failed";+ }+}diff --git a/apps/web/src/lib/oauth/server.ts b/apps/web/src/lib/oauth/server.tsindex 5e57f0cf4..e536a33ce 100644--- a/apps/web/src/lib/oauth/server.ts+++ b/apps/web/src/lib/oauth/server.ts@@ -12,6 +12,7 @@ import * as z from "zod";import { FLASH_MAX_AGE, flashCookieName } from "@/lib/flash/constants";import { validateRedirectUrl } from "@/lib/utils/redirect";import { OAUTH_FLASH_KEY } from "./constants";+import { OAuthConnectionRefusedError } from "./errors";import type { CreateOAuthOptions } from "./types";const logger = createLogger("oauth");@@ -254,11 +255,17 @@ export function OAuthIntegration<T extends string>(setOutcome(c, { connected: id });return c.redirect(new URL(redirectTo, absoluteUrl()).toString());} catch (error) {- logger.error({ error }, "OAuth connection failed");+ const refusal =+ error instanceof OAuthConnectionRefusedError ? error.reason : null;+ if (refusal) {+ logger.warn({ reason: refusal }, "OAuth connection refused");+ } else {+ logger.error({ error }, "OAuth connection failed");+ }const redirectTo = getCookie(c, REDIRECT_TO) || "/";setOutcome(c, {- error: "connection_failed",+ error: refusal ?? "connection_failed",integrationId: c.req.param("id") ?? "",});return c.redirect(new URL(redirectTo, absoluteUrl()).toString());diff --git a/apps/web/src/trpc/client/provider.tsx b/apps/web/src/trpc/client/provider.tsxindex 2717eccce..18097b37f 100644--- a/apps/web/src/trpc/client/provider.tsx+++ b/apps/web/src/trpc/client/provider.tsx@@ -80,6 +80,15 @@ export function TRPCProvider(props: { children: React.ReactNode }) {}),);break;+ // Only Microsoft Teams reports this today, so the copy names it.+ case "CONFERENCING_CANNOT_HOST":+ toast.error(+ t("actionErrorConferencingCannotHost", {+ defaultValue:+ "Microsoft Teams couldn't create the meeting. Check that your Microsoft account has a Teams license and that you can open Teams with it, then try again.",+ }),+ );+ break;case "CONFERENCING_FAILED":toast.error(t("actionErrorConferencingFailed", {@@ -167,6 +176,7 @@ export function TRPCProvider(props: { children: React.ReactNode }) {showErrorToast(error.data.appError === "INVALID_SESSION" ||error.data.appError === "CONFERENCING_NOT_CONNECTED" ||+ error.data.appError === "CONFERENCING_CANNOT_HOST" ||error.data.appError === "CONFERENCING_FAILED"? error.data.appError: error.data.code,diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex c98609a19..38779cf24 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -108,10 +108,13 @@ async function mintConferencing({}const label = conferencingProviderLabels[conferencing.provider];- const code =- result.reason === "not_connected"- ? "CONFERENCING_NOT_CONNECTED"- : "CONFERENCING_FAILED";+ const code = (+ {+ not_connected: "CONFERENCING_NOT_CONNECTED",+ cannot_host: "CONFERENCING_CANNOT_HOST",+ provider_error: "CONFERENCING_FAILED",+ } as const+ )[result.reason];throw new TRPCError({code: "PRECONDITION_FAILED",message: `${label} meeting could not be created (${code})`,