Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add Microsoft Teams as a conferencing provider (#3392)

Luke Vellaaa1fee490e46
diff --git a/apps/docs/api-reference/openapi.json b/apps/docs/api-reference/openapi.json
index 2188bcaf6..a1b5c64e8 100644
--- a/apps/docs/api-reference/openapi.json
+++ b/apps/docs/api-reference/openapi.json
@@ -79,6 +79,18 @@
"provider"
]
},
+ {
+ "type": "object",
+ "properties": {
+ "provider": {
+ "type": "string",
+ "const": "teams"
+ }
+ },
+ "required": [
+ "provider"
+ ]
+ },
{
"type": "object",
"properties": {
@@ -107,7 +119,7 @@
"type": "null"
}
],
- "description": "The video call for the event, or `null`. A `zoom` or `meet` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",
+ "description": "The video call for the event, or `null`. A `zoom`, `meet` or `teams` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",
"example": {
"provider": "zoom"
}
@@ -397,7 +409,7 @@
"maxLength": 255
},
"conferencing": {
- "description": "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
+ "description": "The video call for the event. `zoom`, `meet` and `teams` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
"examples": [
{
"provider": "zoom"
@@ -433,6 +445,18 @@
"provider"
]
},
+ {
+ "type": "object",
+ "properties": {
+ "provider": {
+ "type": "string",
+ "const": "teams"
+ }
+ },
+ "required": [
+ "provider"
+ ]
+ },
{
"type": "object",
"properties": {
@@ -558,7 +582,7 @@
"maxLength": 255
},
"conferencing": {
- "description": "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
+ "description": "The video call for the event. `zoom`, `meet` and `teams` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
"examples": [
{
"provider": "zoom"
@@ -594,6 +618,18 @@
"provider"
]
},
+ {
+ "type": "object",
+ "properties": {
+ "provider": {
+ "type": "string",
+ "const": "teams"
+ }
+ },
+ "required": [
+ "provider"
+ ]
+ },
{
"type": "object",
"properties": {
diff --git a/apps/docs/integrations/microsoft-teams.mdx b/apps/docs/integrations/microsoft-teams.mdx
new file mode 100644
index 000000000..0f31c9031
--- /dev/null
+++ b/apps/docs/integrations/microsoft-teams.mdx
@@ -0,0 +1,142 @@
+---
+icon: video
+title: Microsoft Teams
+description: Connect your Microsoft work or school account so Rallly creates the Teams meeting link when you finalize a poll
+---
+
+With the Microsoft Teams integration, Rallly creates a Teams meeting on your Microsoft account at the moment you finalize a poll. The join link goes into the event, the calendar invite and the confirmation emails, so participants never wait for a link to follow.
+
+## How it works
+
+1. You connect your Microsoft work or school account once, from your settings.
+2. When you create a poll, you choose Microsoft Teams as the video call. The poll shows "Microsoft Teams" to participants while voting is open; there is no link yet.
+3. When you finalize the poll, Rallly creates a Teams meeting for the chosen time on your Microsoft account and attaches the join link to the event.
+
+The meeting is created on the Microsoft account you connected, so it follows your organization's Teams meeting policies, such as the lobby and who can present. Rallly does not change those settings.
+
+## Requirements
+
+- A Microsoft work or school account with a Microsoft Teams license. Personal Microsoft accounts (Outlook.com, Hotmail, Live) are not supported: Microsoft does not let apps create Teams meetings for them, so Rallly asks Microsoft for a work or school account when you connect.
+- You must have used Teams at least once with that account. An account whose Microsoft 365 plan does not include Teams cannot create meetings.
+- Your organization must let you approve Rallly, or an administrator must approve it for the organization. See [Admin approval](#admin-approval).
+- The Microsoft Teams integration must be enabled on the Rallly instance you use. On a self-hosted instance the administrator turns it on.
+- Finalizing a poll is a Pro feature on rallly.co. Connecting Microsoft Teams and choosing it for a poll works on every plan; the meeting is created when the poll is finalized.
+
+## Adding the app
+
+<Steps>
+ <Step title="Open Conferencing settings">
+ In Rallly, open **Settings** from the sidebar and choose **Conferencing**.
+ </Step>
+ <Step title="Connect your account">
+ Next to **Microsoft Teams**, click **Connect**. You are sent to Microsoft to pick your work or school account and sign in.
+ </Step>
+ <Step title="Approve the permissions">
+ Microsoft shows what Rallly is asking for (listed under [Permissions](#permissions)). Click **Accept**. You are returned to Rallly, where the email address of your Microsoft account appears next to Microsoft Teams.
+ </Step>
+</Steps>
+
+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.
+
+### Admin approval
+
+Many organizations do not let their users approve apps themselves. If yours is one of them, Microsoft shows "Need admin approval" instead of the permissions, and Rallly shows an error when you return. Only an administrator of your organization can resolve this.
+
+When the connection fails, Rallly offers a **Copy link** button. Send that link to your IT administrator. The administrator opens it, signs in with their administrator account and approves Rallly for the whole organization; they do not need a Rallly account. On rallly.co the link is:
+
+```
+https://app.rallly.co/api/integrations/admin-consent/microsoft-teams?redirect=/settings/conferencing
+```
+
+On a self-hosted instance, replace `https://app.rallly.co` with the address of your instance.
+
+After the administrator approves, connect Microsoft Teams again. Microsoft no longer asks for approval. Administrators who prefer the Microsoft Entra admin center can grant the same approval under **Enterprise apps**, after searching for Rallly and opening **Permissions**.
+
+## Using the integration
+
+### Choosing Microsoft Teams for a poll
+
+When creating a poll, click **Add location** and choose **Microsoft Teams** under **Video call**. The form shows "Microsoft Teams" as the video call for this poll.
+
+If your Microsoft Teams account is not connected, the form tells you so and links to Conferencing settings.
+
+Participants see "Microsoft Teams" on the poll page while voting is open. No meeting link exists yet.
+
+### Finalizing the poll
+
+When you finalize the poll and pick the winning time, Rallly:
+
+1. Creates a Teams meeting for that time on your Microsoft account.
+2. Attaches the join link, meeting ID and passcode to the event.
+3. Includes them in the calendar invite (`.ics`) and in the confirmation emails sent to you and to participants.
+
+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.
+
+### Which account hosts the meeting
+
+The meeting is created on the Microsoft account of the poll's organizer. If a space member finalizes a poll organized by someone else, the meeting is still created on the organizer's Microsoft account, and the organizer is the host.
+
+## Permissions
+
+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. |
+| 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.
+
+## Data Rallly stores
+
+For a connected Microsoft account, Rallly stores:
+
+- Your Microsoft account id and email address, to identify the connection and show it in your settings.
+- The access token and refresh token Microsoft issues, encrypted at rest, so Rallly can create meetings on your behalf without asking you to sign in each time.
+
+For each finalized poll, Rallly stores the join link, meeting ID and passcode of the meeting it created, as part of the event.
+
+Rallly does not store the content of any meeting.
+
+## Removing the app
+
+### From Rallly
+
+1. Open **Settings**, then **Conferencing**.
+2. Next to **Microsoft Teams**, click the **More options** button and choose **Disconnect**.
+
+The connection is removed immediately, Rallly deletes the tokens it stored for that Microsoft account and stops creating Teams meetings for you.
+
+Microsoft does not let apps revoke their own access, so disconnecting in Rallly does not remove Rallly from your Microsoft account. Rallly no longer holds tokens to use it, but to remove the permission itself, follow the steps below.
+
+Polls that already chose Microsoft Teams keep that choice but can no longer be finalized with a Teams link until an account is connected again. Meetings Rallly already created keep working.
+
+### From your Microsoft account
+
+1. Open [My Apps](https://myapps.microsoft.com) and sign in with the account you connected.
+2. Find **Rallly**, open its menu and choose **Manage your application**.
+3. Choose **Revoke permissions** and confirm.
+
+If you do not see the option, your organization manages app permissions centrally; ask your administrator to remove Rallly. Microsoft does not tell Rallly, so the connection still appears in your settings until you disconnect it in Rallly as well; Rallly can no longer use it.
+
+## Troubleshooting
+
+**Microsoft says "Need admin approval".** Your organization does not let users approve apps. Send your administrator the link described under [Admin approval](#admin-approval).
+
+**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.
+
+**"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.
+
+**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.
+
+**The meeting was created on the wrong account.** The meeting is always created on the poll organizer's connected Microsoft account. Check which account is connected in Conferencing settings.
+
+Still stuck? [Contact support](/contact/support).
diff --git a/apps/docs/self-hosting/single-sign-on.mdx b/apps/docs/self-hosting/single-sign-on.mdx
index 8337fe927..2849de895 100644
--- a/apps/docs/self-hosting/single-sign-on.mdx
+++ b/apps/docs/self-hosting/single-sign-on.mdx
@@ -59,6 +59,16 @@ If `optionalClaims` is `null`, replace it with `{ "idToken": [ ...the four entri
Once the claims are present, a Microsoft sign-in whose address Microsoft does not vouch for fails with "Your email address is not verified". Existing users are not affected. Single-tenant registrations do not need this.
</Accordion>
+<Accordion title="Using the same registration for Microsoft Teams">
+With `CONFERENCING_ENABLED=true`, the Microsoft registration also powers the [Microsoft Teams integration](/integrations/microsoft-teams); there are no separate Teams variables. Add the redirect URI:
+
+```
+https://<YOUR_DOMAIN>/api/integrations/callback/microsoft-teams
+```
+
+Under **API permissions**, add the delegated Microsoft Graph permissions `OnlineMeetings.ReadWrite`, `User.Read` and `offline_access`. If your organization does not let users consent to apps, choose **Grant admin consent** on the same page. Teams meetings can only be created for work or school accounts, so with `MICROSOFT_TENANT_ID` set to `common` or `consumers` Teams connects through the `organizations` endpoint; with a tenant ID it connects through that tenant.
+</Accordion>
+
<ParamField path="MICROSOFT_TENANT_ID">
The tenant ID of your Microsoft application.
</ParamField>
diff --git a/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx b/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx
index 0f5c4444e..3e88425a0 100644
--- a/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx
+++ b/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx
@@ -9,7 +9,7 @@ export default async function PrivacyPolicy() {
cacheLife("max");
return (
<Section>
- <LegalPageLayout title="Privacy policy" lastUpdated="2026-09-26">
+ <LegalPageLayout title="Privacy policy" lastUpdated="2026-09-27">
<p>
At rallly.co, we take your privacy seriously. This privacy policy
explains how we collect, use, and disclose your personal data, and
@@ -192,6 +192,46 @@ export default async function PrivacyPolicy() {
stay in your Zoom account.
</p>
+ <h2>Microsoft user data</h2>
+
+ <p>
+ If you connect Microsoft Teams, Rallly uses the permission to create
+ online meetings (<code>OnlineMeetings.ReadWrite</code>) only to create
+ a meeting on your Microsoft account when you finalize a poll that uses
+ Microsoft Teams as its video call, and reads your Microsoft account
+ id, name and email address to identify the connection. Rallly does not
+ read your other meetings, chats, recordings, files, contacts, calendar
+ or email, and does not join or record meetings.
+ </p>
+
+ <p>
+ We do not store your name. We store your Microsoft account id and
+ email address to identify the connection and show which account is
+ connected, and the access and refresh tokens Microsoft issues,
+ encrypted at rest, so Rallly can create meetings without asking you to
+ sign in each time. For each meeting Rallly creates, we store its join
+ link, meeting id and passcode on the event, so they can be included in
+ the calendar invite and confirmation emails sent to you and your
+ participants.
+ </p>
+
+ <p>
+ We use this data only to identify the connected account and to create
+ meetings for you as the organizer. We do not sell Microsoft user data,
+ use it for advertising, use it to train AI models, or share it with
+ third parties except as needed to provide the service.
+ </p>
+
+ <p>
+ When you disconnect Microsoft Teams in your settings, we delete the
+ stored account details and tokens. When you delete your Rallly
+ account, we delete them along with your events, including the details
+ of meetings Rallly created. Microsoft does not let apps revoke their
+ own access; you can remove Rallly&apos;s permissions at any time at{" "}
+ <a href="https://myapps.microsoft.com">myapps.microsoft.com</a>.
+ Meetings Rallly already created stay in your Microsoft account.
+ </p>
+
<h2>Content moderation</h2>
<p>
diff --git a/apps/web/.env.sample b/apps/web/.env.sample
index 05d983045..f534780e1 100644
--- a/apps/web/.env.sample
+++ b/apps/web/.env.sample
@@ -45,8 +45,14 @@ KV_REST_API_TOKEN=dev_fake_token_123456789abcdefghijklmnop
NEXT_PUBLIC_SELF_HOSTED=false
# Conferencing integrations (optional). Set CONFERENCING_ENABLED=true to let
-# users connect Zoom and Google Meet and add meeting links to their events.
-# Google Meet reuses GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET.
+# users connect Zoom, Google Meet and Microsoft Teams and add meeting links to
+# their events. Google Meet reuses GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET.
+# Microsoft Teams reuses MICROSOFT_CLIENT_ID / MICROSOFT_CLIENT_SECRET: the
+# registration needs the delegated Microsoft Graph permission
+# OnlineMeetings.ReadWrite and the redirect URI
+# <base url>/api/integrations/callback/microsoft-teams. Teams connects through
+# the `organizations` authority when MICROSOFT_TENANT_ID is common or
+# consumers, and through the configured tenant otherwise.
# CONFERENCING_ENABLED=false
# ZOOM_CLIENT_ID=
# ZOOM_CLIENT_SECRET=
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 60629e97f..d355132f4 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -171,12 +171,15 @@
"commentsSheetSubmitted": "Your comment has been added",
"commentsTriggerLabel": "{count, plural, =0 {Comments} one {1 Comment} other {# Comments}}",
"conferencing": "Conferencing",
+ "conferencingAdminConsentDenied": "The app was not approved. People in your organization still can't connect it.",
+ "conferencingAdminConsentGranted": "Approved. People in your organization can now connect this app.",
"conferencingConnected": "Account connected",
"conferencingConnectFailed": "We couldn't connect that account. Please try again.",
"conferencingDescription": "Connect the tools you use for video calls so we can add meeting links to your events.",
"conferencingDisconnected": "Account disconnected",
"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.",
"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/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx b/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx
index 05a8f8ea1..b1b5670dc 100644
--- a/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/calendars/components/calendar-connection-flash.tsx
@@ -19,7 +19,7 @@ export function CalendarConnectionFlash() {
toast.success(
t("calendarConnected", { defaultValue: "Calendar connected" }),
);
- } else {
+ } else if (flash.startsWith("error:")) {
toast.error(
t("calendarConnectFailed", {
defaultValue: "We couldn't connect that calendar. Please try again.",
diff --git a/apps/web/src/app/api/integrations/[...connection]/route.ts b/apps/web/src/app/api/integrations/[...connection]/route.ts
index 692d75a80..90004ad08 100644
--- a/apps/web/src/app/api/integrations/[...connection]/route.ts
+++ b/apps/web/src/app/api/integrations/[...connection]/route.ts
@@ -6,12 +6,15 @@ import {
import {
isConferencingEnabled,
isConferencingProviderAllowedFor,
+ MICROSOFT_TEAMS_SCOPES,
} from "@/features/conferencing/constants";
import { createConferencingConnection } from "@/features/conferencing/mutations";
import type { ConferencingProvider } from "@/features/conferencing/schema";
+import { getMicrosoftTeamsAuthority } from "@/features/conferencing/utils";
import { saveOAuthCredentials } from "@/features/credentials/mutations";
import { getSession } from "@/lib/auth";
import { GoogleOAuthClient } from "@/lib/oauth/providers/google";
+import { MicrosoftOAuthClient } from "@/lib/oauth/providers/microsoft";
import { ZoomOAuthClient } from "@/lib/oauth/providers/zoom";
import { OAuthIntegration } from "@/lib/oauth/server";
import type { OAuthClient } from "@/lib/oauth/types";
@@ -20,6 +23,7 @@ type Integration =
| "google-calendar"
| "outlook-calendar"
| "google-meet"
+ | "microsoft-teams"
| "zoom";
async function requireSessionUserId() {
@@ -69,7 +73,7 @@ function conferencingOnConnect({
const { handler } = OAuthIntegration<Integration>({
basePath: "/api/integrations",
- getIntegration: async ({ integrationId, callbackUrl }) => {
+ getIntegration: async ({ integrationId, callbackUrl, flow }) => {
switch (integrationId) {
case "google-calendar": {
if (!env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET) {
@@ -160,6 +164,30 @@ const { handler } = OAuthIntegration<Integration>({
}),
});
}
+ case "microsoft-teams": {
+ if (
+ !isConferencingEnabled ||
+ !env.MICROSOFT_CLIENT_ID ||
+ !env.MICROSOFT_CLIENT_SECRET ||
+ // The rollout allowlist limits who connects. Approving the app for
+ // an organization connects no one, and the administrator doing it
+ // is rarely on the list or signed in to Rallly.
+ (flow === "connect" && !(await isAllowedForSession("teams")))
+ ) {
+ return null;
+ }
+ return new MicrosoftOAuthClient({
+ tenant: getMicrosoftTeamsAuthority(env.MICROSOFT_TENANT_ID),
+ clientId: env.MICROSOFT_CLIENT_ID,
+ clientSecret: env.MICROSOFT_CLIENT_SECRET,
+ callbackUrl,
+ scopes: MICROSOFT_TEAMS_SCOPES,
+ onConnect: conferencingOnConnect({
+ integrationId,
+ displayName: "Microsoft Teams",
+ }),
+ });
+ }
default:
return null;
}
diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.ts
index dd45c850d..a0a3b8fcc 100644
--- a/apps/web/src/app/api/v1/schemas.ts
+++ b/apps/web/src/app/api/v1/schemas.ts
@@ -181,7 +181,7 @@ const pollSettingsFields = {
}),
conferencing: pollConferencingSchema.optional().meta({
description:
- "The video call for the event. `zoom` and `meet` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
+ "The video call for the event. `zoom`, `meet` and `teams` need the organizer to have connected that account in their Conferencing settings; the meeting link is created when the poll is finalized. `custom` names any call, with an optional link participants join with.",
examples: [
{ provider: "zoom" },
{
@@ -446,7 +446,7 @@ const pollSchema = z
location: z.string().nullable().meta({ example: "Conference Room A" }),
conferencing: pollConferencingSchema.nullable().meta({
description:
- "The video call for the event, or `null`. A `zoom` or `meet` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",
+ "The video call for the event, or `null`. A `zoom`, `meet` or `teams` entry has no link until the poll is finalized; a `custom` entry carries the organizer's label and, when given, the link.",
example: { provider: "zoom" },
}),
timeZone: z.string().nullable().meta({ example: "Europe/London" }),
diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts
index 75202b537..1fcfc4f51 100644
--- a/apps/web/src/env.ts
+++ b/apps/web/src/env.ts
@@ -110,8 +110,9 @@ export const env = createEnv({
GOOGLE_CLIENT_SECRET: z.string().optional(),
/**
- * Conferencing integrations (Zoom, Google Meet). The flag needs at least
- * one provider's OAuth app configured; see createFinalSchema below.
+ * Conferencing integrations (Zoom, Google Meet, Microsoft Teams). The
+ * flag needs at least one provider's OAuth app configured; see
+ * createFinalSchema below.
*/
CONFERENCING_ENABLED: z.enum(["true", "false"]).default("false"),
ZOOM_CLIENT_ID: z.string().optional(),
@@ -122,9 +123,10 @@ export const env = createEnv({
// provider: an unpublished or unverified OAuth app authorizes no one else.
ZOOM_ALLOWED_EMAILS: z.string().optional(),
GOOGLE_MEET_ALLOWED_EMAILS: z.string().optional(),
+ MICROSOFT_TEAMS_ALLOWED_EMAILS: z.string().optional(),
/**
- * Microsoft Integration
+ * Microsoft app registration, shared by sign in and Microsoft Teams.
*/
MICROSOFT_TENANT_ID: z.string().optional().default("common"),
MICROSOFT_CLIENT_ID: z.string().optional(),
@@ -300,6 +302,7 @@ export const env = createEnv({
ZOOM_WEBHOOK_SECRET_TOKEN: process.env.ZOOM_WEBHOOK_SECRET_TOKEN,
ZOOM_ALLOWED_EMAILS: process.env.ZOOM_ALLOWED_EMAILS,
GOOGLE_MEET_ALLOWED_EMAILS: process.env.GOOGLE_MEET_ALLOWED_EMAILS,
+ MICROSOFT_TEAMS_ALLOWED_EMAILS: process.env.MICROSOFT_TEAMS_ALLOWED_EMAILS,
MICROSOFT_TENANT_ID: process.env.MICROSOFT_TENANT_ID,
MICROSOFT_CLIENT_ID: process.env.MICROSOFT_CLIENT_ID,
MICROSOFT_CLIENT_SECRET: process.env.MICROSOFT_CLIENT_SECRET,
@@ -353,12 +356,20 @@ export const env = createEnv({
const hasGoogle = Boolean(
env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET,
);
- if (env.CONFERENCING_ENABLED === "true" && !hasZoom && !hasGoogle) {
+ const hasMicrosoft = Boolean(
+ env.MICROSOFT_CLIENT_ID && env.MICROSOFT_CLIENT_SECRET,
+ );
+ if (
+ env.CONFERENCING_ENABLED === "true" &&
+ !hasZoom &&
+ !hasGoogle &&
+ !hasMicrosoft
+ ) {
ctx.addIssue({
code: "custom",
path: ["CONFERENCING_ENABLED"],
message:
- "CONFERENCING_ENABLED is set but no conferencing provider is configured. Set ZOOM_CLIENT_ID and ZOOM_CLIENT_SECRET for Zoom, or GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET for Google Meet, or turn the flag off.",
+ "CONFERENCING_ENABLED is set but no conferencing provider is configured. Set ZOOM_CLIENT_ID and ZOOM_CLIENT_SECRET for Zoom, GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET for Google Meet, or MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET for Microsoft Teams, or turn the flag off.",
});
}
}),
diff --git a/apps/web/src/features/conferencing/assets/microsoft-teams.svg b/apps/web/src/features/conferencing/assets/microsoft-teams.svg
new file mode 100644
index 000000000..399243a1d
--- /dev/null
+++ b/apps/web/src/features/conferencing/assets/microsoft-teams.svg
@@ -0,0 +1 @@
+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="none"><path fill="#5059C9" d="M10.765 6.875h3.616c.342 0 .619.276.619.617v3.288a2.272 2.272 0 01-2.274 2.27h-.01a2.272 2.272 0 01-2.274-2.27V7.199c0-.179.145-.323.323-.323zM13.21 6.225c.808 0 1.464-.655 1.464-1.462 0-.808-.656-1.463-1.465-1.463s-1.465.655-1.465 1.463c0 .807.656 1.462 1.465 1.462z"/><path fill="#7B83EB" d="M8.651 6.225a2.114 2.114 0 002.117-2.112A2.114 2.114 0 008.65 2a2.114 2.114 0 00-2.116 2.112c0 1.167.947 2.113 2.116 2.113zM11.473 6.875h-5.97a.611.611 0 00-.596.625v3.75A3.669 3.669 0 008.488 15a3.669 3.669 0 003.582-3.75V7.5a.611.611 0 00-.597-.625z"/><path fill="#000000" d="M8.814 6.875v5.255a.598.598 0 01-.596.595H5.193a3.951 3.951 0 01-.287-1.476V7.5a.61.61 0 01.597-.624h3.31z" opacity=".1"/><path fill="#000000" d="M8.488 6.875v5.58a.6.6 0 01-.596.595H5.347a3.22 3.22 0 01-.267-.65 3.951 3.951 0 01-.172-1.15V7.498a.61.61 0 01.596-.624h2.985z" opacity=".2"/><path fill="#000000" d="M8.488 6.875v4.93a.6.6 0 01-.596.595H5.08a3.951 3.951 0 01-.172-1.15V7.498a.61.61 0 01.596-.624h2.985z" opacity=".2"/><path fill="#000000" d="M8.163 6.875v4.93a.6.6 0 01-.596.595H5.079a3.951 3.951 0 01-.172-1.15V7.498a.61.61 0 01.596-.624h2.66z" opacity=".2"/><path fill="#000000" d="M8.814 5.195v1.024c-.055.003-.107.006-.163.006-.055 0-.107-.003-.163-.006A2.115 2.115 0 016.593 4.6h1.625a.598.598 0 01.596.594z" opacity=".1"/><path fill="#000000" d="M8.488 5.52v.699a2.115 2.115 0 01-1.79-1.293h1.195a.598.598 0 01.595.594z" opacity=".2"/><path fill="#000000" d="M8.488 5.52v.699a2.115 2.115 0 01-1.79-1.293h1.195a.598.598 0 01.595.594z" opacity=".2"/><path fill="#000000" d="M8.163 5.52v.647a2.115 2.115 0 01-1.465-1.242h.87a.598.598 0 01.595.595z" opacity=".2"/><path fill="url(#microsoft-teams-tile)" d="M1.597 4.925h5.969c.33 0 .597.267.597.596v5.958a.596.596 0 01-.597.596h-5.97A.596.596 0 011 11.479V5.521c0-.33.267-.596.597-.596z"/><path fill="#ffffff" d="M6.152 7.193H4.959v3.243h-.76V7.193H3.01v-.63h3.141v.63z"/><defs><linearGradient id="microsoft-teams-tile" x1="2.244" x2="6.906" y1="4.46" y2="12.548" gradientUnits="userSpaceOnUse"><stop stop-color="#5A62C3"/><stop offset=".5" stop-color="#4D55BD"/><stop offset="1" stop-color="#3940AB"/></linearGradient></defs></svg>
diff --git a/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx
index 147d6705a..0dbd6040a 100644
--- a/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx
+++ b/apps/web/src/features/conferencing/components/conferencing-connection-flash.tsx
@@ -2,14 +2,21 @@
import { toast } from "@rallly/ui/sonner";
import React from "react";
+import { useCopyToClipboard } from "react-use";
import { useTranslation } from "@/i18n/client";
import { useFlash } from "@/lib/flash/client";
import { OAUTH_FLASH_KEY } from "@/lib/oauth/constants";
+// Organizations can require an administrator to approve Teams before their
+// users may connect it; this link lets the administrator grant it.
+const teamsAdminConsentPath =
+ "/api/integrations/admin-consent/microsoft-teams?redirect=/settings/conferencing";
+
// Surfaces the outcome of the OAuth round trip once the user lands back here.
export function ConferencingConnectionFlash() {
const { t } = useTranslation();
const flash = useFlash(OAUTH_FLASH_KEY);
+ const [, copy] = useCopyToClipboard();
React.useEffect(() => {
if (!flash) return;
@@ -17,14 +24,51 @@ export function ConferencingConnectionFlash() {
toast.success(
t("conferencingConnected", { defaultValue: "Account connected" }),
);
- } else {
+ } else if (flash.startsWith("admin_consent:")) {
+ toast.success(
+ t("conferencingAdminConsentGranted", {
+ defaultValue:
+ "Approved. People in your organization can now connect this app.",
+ }),
+ );
+ } else if (flash.startsWith("error:admin_consent_denied:")) {
+ toast.error(
+ t("conferencingAdminConsentDenied", {
+ defaultValue:
+ "The app was not approved. People in your organization still can't connect it.",
+ }),
+ );
+ } 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.
+ toast.error(
+ t("conferencingConnectFailed", {
+ defaultValue: "We couldn't connect that account. Please try again.",
+ }),
+ {
+ description: t("conferencingTeamsAdminConsentHint", {
+ defaultValue:
+ "If your organization requires admin approval, send this link to your IT administrator.",
+ }),
+ duration: Number.POSITIVE_INFINITY,
+ closeButton: true,
+ action: {
+ label: t("copyLink", { defaultValue: "Copy link" }),
+ onClick: () => {
+ copy(new URL(teamsAdminConsentPath, window.location.origin).href);
+ toast.success(t("copied", { defaultValue: "Copied" }));
+ },
+ },
+ },
+ );
+ } else if (flash.startsWith("error:")) {
toast.error(
t("conferencingConnectFailed", {
defaultValue: "We couldn't connect that account. Please try again.",
}),
);
}
- }, [flash, t]);
+ }, [flash, t, copy]);
return null;
}
diff --git a/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx b/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx
index 11fb6acb9..cd12143f7 100644
--- a/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx
+++ b/apps/web/src/features/conferencing/components/conferencing-provider-icon.tsx
@@ -1,4 +1,5 @@
import GoogleMeetIcon from "@/features/conferencing/assets/google-meet.svg";
+import MicrosoftTeamsIcon from "@/features/conferencing/assets/microsoft-teams.svg";
import ZoomIcon from "@/features/conferencing/assets/zoom.svg";
import type { ConferencingProvider } from "@/features/conferencing/schema";
@@ -14,5 +15,9 @@ export function ConferencingProviderIcon({
return <ZoomIcon width={size} height={size} aria-hidden="true" />;
case "meet":
return <GoogleMeetIcon width={size} height={size} aria-hidden="true" />;
+ case "teams":
+ return (
+ <MicrosoftTeamsIcon width={size} height={size} aria-hidden="true" />
+ );
}
}
diff --git a/apps/web/src/features/conferencing/constants.ts b/apps/web/src/features/conferencing/constants.ts
index db0a12f75..9f837cb43 100644
--- a/apps/web/src/features/conferencing/constants.ts
+++ b/apps/web/src/features/conferencing/constants.ts
@@ -5,7 +5,8 @@ export const isConferencingEnabled =
process.env.CONFERENCING_ENABLED === "true";
// A provider is offered when its OAuth app is configured; Google Meet reuses
-// the Google OAuth app the calendars integration already needs.
+// the Google OAuth app the calendars integration already needs, and Microsoft
+// Teams the Microsoft app sign in uses.
export function getAvailableConferencingProviders(): ConferencingProvider[] {
if (!isConferencingEnabled) {
return [];
@@ -17,6 +18,9 @@ export function getAvailableConferencingProviders(): ConferencingProvider[] {
if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
providers.push("meet");
}
+ if (process.env.MICROSOFT_CLIENT_ID && process.env.MICROSOFT_CLIENT_SECRET) {
+ providers.push("teams");
+ }
return providers;
}
@@ -27,6 +31,7 @@ export function getAvailableConferencingProviders(): ConferencingProvider[] {
const providerAllowlists: Record<ConferencingProvider, string | undefined> = {
zoom: process.env.ZOOM_ALLOWED_EMAILS,
meet: process.env.GOOGLE_MEET_ALLOWED_EMAILS,
+ teams: process.env.MICROSOFT_TEAMS_ALLOWED_EMAILS,
};
export function isConferencingProviderAllowedFor({
@@ -51,3 +56,13 @@ export function getAvailableConferencingProvidersFor({
isConferencingProviderAllowedFor({ provider, email }),
);
}
+
+// `offline_access` is what makes Microsoft issue a refresh token.
+export const MICROSOFT_TEAMS_SCOPES = [
+ "openid",
+ "profile",
+ "email",
+ "offline_access",
+ "User.Read",
+ "OnlineMeetings.ReadWrite",
+];
diff --git a/apps/web/src/features/conferencing/schema.ts b/apps/web/src/features/conferencing/schema.ts
index ce4fd73b0..30cbafec3 100644
--- a/apps/web/src/features/conferencing/schema.ts
+++ b/apps/web/src/features/conferencing/schema.ts
@@ -2,7 +2,7 @@ import * as z from "zod";
// Providers Rallly can mint links for. Distinct from the stored-link union
// below, which also covers links pasted by hand (custom) and phone dial-ins.
-export const conferencingProviderSchema = z.enum(["zoom", "meet"]);
+export const conferencingProviderSchema = z.enum(["zoom", "meet", "teams"]);
export type ConferencingProvider = z.infer<typeof conferencingProviderSchema>;
// What a poll records before there is a link: a provider to mint with at
@@ -12,6 +12,7 @@ export type ConferencingProvider = z.infer<typeof conferencingProviderSchema>;
export const pollConferencingSchema = z.discriminatedUnion("provider", [
z.object({ provider: z.literal("zoom") }),
z.object({ provider: z.literal("meet") }),
+ z.object({ provider: z.literal("teams") }),
z.object({
provider: z.literal("custom"),
label: z.string().trim().min(1).max(100),
diff --git a/apps/web/src/features/conferencing/service.ts b/apps/web/src/features/conferencing/service.ts
index 4c910dfe8..39b2540d7 100644
--- a/apps/web/src/features/conferencing/service.ts
+++ b/apps/web/src/features/conferencing/service.ts
@@ -1,17 +1,23 @@
import "server-only";
import { createLogger } from "@rallly/logger";
+import { OAuth2RequestError } from "arctic";
import { google } from "googleapis";
import { env } from "@/env";
import { loadCredential } from "@/features/credentials/data";
import { updateOAuthCredentialTokens } from "@/features/credentials/mutations";
import type { OAuthCredentials } from "@/features/credentials/schema";
+import { MicrosoftOAuthClient } from "@/lib/oauth/providers/microsoft";
import { ZoomOAuthClient } from "@/lib/oauth/providers/zoom";
+import { MICROSOFT_TEAMS_SCOPES } from "./constants";
import { getConferencingConnectionForProvider } from "./data";
import type { Conferencing, ConferencingProvider } from "./schema";
import {
+ getMicrosoftTeamsAuthority,
meetSpaceResponseSchema,
meetSpaceToConferencing,
+ teamsMeetingResponseSchema,
+ teamsMeetingToConferencing,
zoomMeetingResponseSchema,
zoomMeetingToConferencing,
} from "./utils";
@@ -71,8 +77,27 @@ export async function createConferencingMeeting({
const conferencing = await createMeetSpace(credential.secret);
return { ok: true, conferencing };
}
+ case "teams": {
+ const secret = await refreshMicrosoftTokenIfExpired({ credential });
+ const conferencing = await createTeamsMeeting({
+ accessToken: secret.accessToken,
+ title,
+ start,
+ end,
+ });
+ return { ok: true, conferencing };
+ }
}
} catch (error) {
+ // The grant is gone (expired after inactivity, password change, revoked
+ // by the user or their admin); only reconnecting brings it back.
+ if (error instanceof OAuth2RequestError && error.code === "invalid_grant") {
+ logger.warn(
+ { userId, provider, connectionId: connection.id },
+ "Conferencing grant is no longer valid",
+ );
+ return { ok: false, reason: "not_connected" };
+ }
// `err` is the key pino's default serializer expands; `error` logs as {}.
logger.error(
{ err: error, userId, provider, connectionId: connection.id },
@@ -82,18 +107,22 @@ export async function createConferencingMeeting({
}
}
-async function refreshZoomTokenIfExpired({
- credential,
-}: {
- credential: NonNullable<Awaited<ReturnType<typeof loadCredential>>>;
-}): Promise<OAuthCredentials> {
+type StoredCredential = NonNullable<Awaited<ReturnType<typeof loadCredential>>>;
+
+// Checked a minute early so a token that expires mid-request is not used.
+function isAccessTokenFresh(credential: StoredCredential) {
const expiresAt = credential.secret.expiresAt
? new Date(credential.secret.expiresAt)
: credential.expiresAt;
- // Refresh a minute early so a token that expires mid-request is not used.
- const isFresh = expiresAt && expiresAt.getTime() - 60_000 > Date.now();
+ return Boolean(expiresAt && expiresAt.getTime() - 60_000 > Date.now());
+}
- if (isFresh || !credential.secret.refreshToken) {
+async function refreshZoomTokenIfExpired({
+ credential,
+}: {
+ credential: StoredCredential;
+}): Promise<OAuthCredentials> {
+ if (isAccessTokenFresh(credential) || !credential.secret.refreshToken) {
return credential.secret;
}
@@ -122,12 +151,49 @@ async function refreshZoomTokenIfExpired({
scopes: tokens.scopes,
};
}
+
+async function refreshMicrosoftTokenIfExpired({
+ credential,
+}: {
+ credential: StoredCredential;
+}): Promise<OAuthCredentials> {
+ if (isAccessTokenFresh(credential) || !credential.secret.refreshToken) {
+ return credential.secret;
+ }
+
+ if (!env.MICROSOFT_CLIENT_ID || !env.MICROSOFT_CLIENT_SECRET) {
+ throw new Error("Microsoft is not configured");
+ }
+
+ const client = new MicrosoftOAuthClient({
+ tenant: getMicrosoftTeamsAuthority(env.MICROSOFT_TENANT_ID),
+ clientId: env.MICROSOFT_CLIENT_ID,
+ clientSecret: env.MICROSOFT_CLIENT_SECRET,
+ scopes: MICROSOFT_TEAMS_SCOPES,
+ });
+
+ const tokens = await client.refreshAccessToken(
+ credential.secret.refreshToken,
+ );
+
+ // Every refresh returns a new refresh token; persist it before the meeting
+ // call so a failure there does not leave the stored one behind.
+ await updateOAuthCredentialTokens({ id: credential.id, tokens });
+
+ return {
+ accessToken: tokens.accessToken,
+ refreshToken: tokens.refreshToken,
+ expiresAt: tokens.expiresAt?.toISOString(),
+ scopes: tokens.scopes,
+ };
+}
+
// Best effort: the tokens are already deleted locally, and a grant Zoom still
// holds is one the user can remove from their own Zoom app list.
export async function revokeZoomToken({
credential,
}: {
- credential: NonNullable<Awaited<ReturnType<typeof loadCredential>>>;
+ credential: StoredCredential;
}) {
const { secret } = credential;
if (!env.ZOOM_CLIENT_ID || !env.ZOOM_CLIENT_SECRET) {
@@ -144,12 +210,8 @@ export async function revokeZoomToken({
// Zoom rejects an expired access token, and they only live an hour, so
// one that is stale, close to expiry or of unknown age is exchanged in
// memory first, with the same margin refreshZoomTokenIfExpired uses.
- const expiresAt = secret.expiresAt
- ? new Date(secret.expiresAt)
- : credential.expiresAt;
- const isFresh = expiresAt && expiresAt.getTime() - 60_000 > Date.now();
const accessToken =
- !isFresh && secret.refreshToken
+ !isAccessTokenFresh(credential) && secret.refreshToken
? (await client.refreshAccessToken(secret.refreshToken)).accessToken
: secret.accessToken;
await client.revokeToken(accessToken);
@@ -201,6 +263,46 @@ async function createZoomMeeting({
);
}
+// Graph does not add the meeting to the organizer's Outlook calendar; the
+// event's own invite carries it.
+async function createTeamsMeeting({
+ accessToken,
+ title,
+ start,
+ end,
+}: {
+ accessToken: string;
+ title: string;
+ 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(),
+ }),
+ },
+ );
+
+ if (!res.ok) {
+ throw new Error(
+ `Teams meeting creation failed with status ${res.status}: ${await res.text()}`,
+ );
+ }
+
+ return teamsMeetingToConferencing(
+ teamsMeetingResponseSchema.parse(await res.json()),
+ );
+}
+
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.ts
index d852ba2e5..825484dda 100644
--- a/apps/web/src/features/conferencing/utils.test.ts
+++ b/apps/web/src/features/conferencing/utils.test.ts
@@ -4,9 +4,12 @@ import { conferencingSchema } from "./schema";
import {
createZoomUrlValidationResponse,
getConferencingUri,
+ getMicrosoftTeamsAuthority,
isEmailAllowlisted,
meetSpaceResponseSchema,
meetSpaceToConferencing,
+ teamsMeetingResponseSchema,
+ teamsMeetingToConferencing,
verifyZoomWebhookSignature,
zoomMeetingResponseSchema,
zoomMeetingToConferencing,
@@ -71,6 +74,63 @@ describe("meetSpaceToConferencing", () => {
});
});
+describe("teamsMeetingToConferencing", () => {
+ it("maps a Teams meeting into the stored link shape", () => {
+ const meeting = teamsMeetingResponseSchema.parse({
+ id: "MSpkYzE3",
+ joinWebUrl:
+ "https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0",
+ subject: "ignored",
+ joinMeetingIdSettings: {
+ isPasscodeRequired: true,
+ joinMeetingId: "1234567890",
+ passcode: "Xy7Zq2",
+ },
+ audioConferencing: null,
+ });
+ const conferencing = teamsMeetingToConferencing(meeting);
+ expect(conferencing).toEqual({
+ provider: "teams",
+ uri: "https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0",
+ meetingId: "1234567890",
+ password: "Xy7Zq2",
+ });
+ expect(conferencingSchema.parse(conferencing)).toEqual(conferencing);
+ });
+
+ it("keeps the link when Graph omits the meeting id settings", () => {
+ const meeting = teamsMeetingResponseSchema.parse({
+ joinWebUrl: "https://teams.microsoft.com/l/meetup-join/abc",
+ joinMeetingIdSettings: null,
+ });
+ expect(teamsMeetingToConferencing(meeting)).toEqual({
+ provider: "teams",
+ uri: "https://teams.microsoft.com/l/meetup-join/abc",
+ meetingId: undefined,
+ password: undefined,
+ });
+ });
+
+ it("rejects a meeting without a join link", () => {
+ expect(teamsMeetingResponseSchema.safeParse({ id: "abc" }).success).toBe(
+ false,
+ );
+ });
+});
+
+describe("getMicrosoftTeamsAuthority", () => {
+ it("keeps personal accounts out of a multitenant registration", () => {
+ expect(getMicrosoftTeamsAuthority("common")).toBe("organizations");
+ expect(getMicrosoftTeamsAuthority("consumers")).toBe("organizations");
+ expect(getMicrosoftTeamsAuthority("organizations")).toBe("organizations");
+ });
+
+ it("keeps a single tenant registration on its tenant", () => {
+ const tenantId = "6d0cfca5-dad4-4d15-a6cf-1552842fab87";
+ expect(getMicrosoftTeamsAuthority(tenantId)).toBe(tenantId);
+ });
+});
+
describe("verifyZoomWebhookSignature", () => {
const secretToken = "zoom-secret-token";
const body = JSON.stringify({ event: "app_deauthorized" });
diff --git a/apps/web/src/features/conferencing/utils.ts b/apps/web/src/features/conferencing/utils.ts
index cb81805ff..7b544df31 100644
--- a/apps/web/src/features/conferencing/utils.ts
+++ b/apps/web/src/features/conferencing/utils.ts
@@ -2,13 +2,15 @@ import * as z from "zod";
import type { Conferencing, ConferencingProvider } from "./schema";
// Which OAuth integration backs each provider. Google Meet shares the Google
-// OAuth app (and credential row) with Google Calendar.
+// OAuth app (and credential row) with Google Calendar; Microsoft Teams shares
+// the Microsoft app with sign in.
export const conferencingProviderIntegrations: Record<
ConferencingProvider,
{ integrationId: string; oauthProvider: string }
> = {
zoom: { integrationId: "zoom", oauthProvider: "zoom" },
meet: { integrationId: "google-meet", oauthProvider: "google" },
+ teams: { integrationId: "microsoft-teams", oauthProvider: "microsoft" },
};
export function integrationIdToConferencingProvider(
@@ -28,6 +30,7 @@ export const conferencingProviderLabels: Record<ConferencingProvider, string> =
{
zoom: "Zoom",
meet: "Google Meet",
+ teams: "Microsoft Teams",
};
export const zoomMeetingResponseSchema = z.object({
@@ -62,6 +65,37 @@ export function meetSpaceToConferencing(
};
}
+export const teamsMeetingResponseSchema = z.object({
+ joinWebUrl: z.url(),
+ joinMeetingIdSettings: z
+ .object({
+ joinMeetingId: z.string().nullish(),
+ passcode: z.string().nullish(),
+ })
+ .nullish(),
+});
+
+export function teamsMeetingToConferencing(
+ meeting: z.infer<typeof teamsMeetingResponseSchema>,
+): Conferencing {
+ return {
+ provider: "teams",
+ uri: meeting.joinWebUrl,
+ meetingId: meeting.joinMeetingIdSettings?.joinMeetingId || undefined,
+ password: meeting.joinMeetingIdSettings?.passcode || undefined,
+ };
+}
+
+// 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 single
+// tenant registration keeps its own tenant.
+export function getMicrosoftTeamsAuthority(tenantId: string) {
+ return tenantId === "common" || tenantId === "consumers"
+ ? "organizations"
+ : tenantId;
+}
+
// Returns the URI suitable for an href / ICS CONFERENCE value.
// Phone numbers are formatted as `tel:` with DTMF pause + extension if present.
export function getConferencingUri(conferencing: Conferencing): string {
diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsx
index 97509cfdf..05bcb288f 100644
--- a/apps/web/src/features/poll/components/create-poll.tsx
+++ b/apps/web/src/features/poll/components/create-poll.tsx
@@ -40,6 +40,7 @@ const toPollConferencing = (
switch (data.conferencingProvider) {
case "zoom":
case "meet":
+ case "teams":
return { provider: data.conferencingProvider };
case "custom": {
const uri = data.conferencingUrl?.trim();
diff --git a/apps/web/src/lib/oauth/constants.ts b/apps/web/src/lib/oauth/constants.ts
index 34f1fd761..34de01d8c 100644
--- a/apps/web/src/lib/oauth/constants.ts
+++ b/apps/web/src/lib/oauth/constants.ts
@@ -1,3 +1,4 @@
// Flash key the OAuth callback writes and settings pages read (`lib/flash`).
-// Value is `connected:<integrationId>` or `error:<code>`.
+// Value is `connected:<integrationId>`, `admin_consent:<integrationId>` or
+// `error:<code>:<integrationId>`.
export const OAUTH_FLASH_KEY = "oauth";
diff --git a/apps/web/src/lib/oauth/providers/microsoft.ts b/apps/web/src/lib/oauth/providers/microsoft.ts
new file mode 100644
index 000000000..ce697abd8
--- /dev/null
+++ b/apps/web/src/lib/oauth/providers/microsoft.ts
@@ -0,0 +1,146 @@
+import "server-only";
+
+import { MicrosoftEntraId } from "arctic";
+import * as z from "zod";
+import type { OAuthClient, OAuthTokens, UserInfo } from "../types";
+import { handleOAuthError } from "./base";
+
+const microsoftUserSchema = z.object({
+ id: z.string(),
+ mail: z.string().nullish(),
+ userPrincipalName: z.string().nullish(),
+ displayName: z.string().nullish(),
+});
+
+interface MicrosoftOAuthClientConfig {
+ tenant: string;
+ clientId: string;
+ clientSecret: string;
+ callbackUrl?: string;
+ scopes: string[];
+ onConnect?: OAuthClient["onConnect"];
+}
+
+export class MicrosoftOAuthClient implements OAuthClient {
+ provider = "microsoft";
+ private client: MicrosoftEntraId;
+ private tenant: string;
+ private clientId: string;
+ private callbackUrl: string;
+ scopes: string[];
+ onConnect?: OAuthClient["onConnect"];
+
+ constructor({
+ tenant,
+ clientId,
+ clientSecret,
+ scopes,
+ callbackUrl = "",
+ onConnect,
+ }: MicrosoftOAuthClientConfig) {
+ this.client = new MicrosoftEntraId(
+ tenant,
+ clientId,
+ clientSecret,
+ callbackUrl,
+ );
+ this.tenant = tenant;
+ this.clientId = clientId;
+ this.callbackUrl = callbackUrl;
+ this.scopes = scopes;
+ this.onConnect = onConnect;
+ }
+
+ getAuthorizationUrl(state: string, codeVerifier: string): URL {
+ const url = this.client.createAuthorizationURL(
+ state,
+ codeVerifier,
+ this.scopes,
+ );
+ // Without it Microsoft silently reuses whichever account the browser is
+ // signed in to, which is often not the one that holds the Teams license.
+ url.searchParams.set("prompt", "select_account");
+ return url;
+ }
+
+ // Tenant wide consent for organizations that do not let users consent to
+ // apps themselves. Microsoft returns the admin to the callback with
+ // `admin_consent` set instead of a code.
+ getAdminConsentUrl(state: string): URL {
+ const url = new URL(
+ `https://login.microsoftonline.com/${this.tenant}/adminconsent`,
+ );
+ url.searchParams.set("client_id", this.clientId);
+ url.searchParams.set("redirect_uri", this.callbackUrl);
+ url.searchParams.set("state", state);
+ return url;
+ }
+
+ async exchangeCode(code: string, codeVerifier: string): Promise<OAuthTokens> {
+ try {
+ const tokens = await this.client.validateAuthorizationCode(
+ code,
+ codeVerifier,
+ );
+ return {
+ accessToken: tokens.accessToken(),
+ refreshToken: tokens.hasRefreshToken()
+ ? tokens.refreshToken()
+ : undefined,
+ expiresAt: tokens.accessTokenExpiresAt(),
+ scopes: tokens.hasScopes() ? tokens.scopes() : this.scopes,
+ };
+ } catch (error) {
+ handleOAuthError(error);
+ }
+ }
+
+ async getUserInfo(tokens: OAuthTokens): Promise<UserInfo> {
+ try {
+ const res = await fetch(
+ "https://graph.microsoft.com/v1.0/me?$select=id,mail,userPrincipalName,displayName",
+ { headers: { Authorization: `Bearer ${tokens.accessToken}` } },
+ );
+ if (!res.ok) {
+ throw new Error(
+ `Microsoft user lookup failed with status ${res.status}`,
+ );
+ }
+ const user = microsoftUserSchema.parse(await res.json());
+ // `mail` is empty for accounts without an Exchange mailbox; the UPN is
+ // the address they sign in with.
+ const email = user.mail || user.userPrincipalName;
+ if (!email) {
+ throw new Error("Missing required user information from Microsoft");
+ }
+ return {
+ id: user.id,
+ email,
+ name: user.displayName || undefined,
+ };
+ } catch (error) {
+ handleOAuthError(error);
+ }
+ }
+
+ // Microsoft rotates the refresh token on every refresh, and a refresh token
+ // is not bound to a scope, so the scopes are named again on each call.
+ async refreshAccessToken(refreshToken: string): Promise<OAuthTokens> {
+ try {
+ const tokens = await this.client.refreshAccessToken(
+ refreshToken,
+ this.scopes,
+ );
+ return {
+ accessToken: tokens.accessToken(),
+ refreshToken: tokens.hasRefreshToken()
+ ? tokens.refreshToken()
+ : refreshToken,
+ expiresAt: tokens.accessTokenExpiresAt(),
+ scopes: tokens.hasScopes() ? tokens.scopes() : this.scopes,
+ };
+ } catch (error) {
+ handleOAuthError(error);
+ }
+ }
+}
diff --git a/apps/web/src/lib/oauth/server.ts b/apps/web/src/lib/oauth/server.ts
index ad1d254a2..5e57f0cf4 100644
--- a/apps/web/src/lib/oauth/server.ts
+++ b/apps/web/src/lib/oauth/server.ts
@@ -6,7 +6,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";
import { generateCodeVerifier, generateState } from "arctic";
import type { Context } from "hono";
import { Hono } from "hono";
-import { getCookie, setCookie } from "hono/cookie";
+import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { handle } from "hono/vercel";
import * as z from "zod";
import { FLASH_MAX_AGE, flashCookieName } from "@/lib/flash/constants";
@@ -34,27 +34,35 @@ export function OAuthIntegration<T extends string>(
const CODE_VERIFIER = `${prefix}code-verifier`;
const REDIRECT_TO = `${prefix}redirect-to`;
const STATE = `${prefix}state`;
+ // Marks a browser that started an admin consent grant, so a decline, which
+ // Microsoft reports with `error` and no `admin_consent`, is told apart from
+ // a user declining an ordinary connect.
+ const ADMIN_CONSENT = `${prefix}admin-consent`;
// Outcome travels as a one-shot flash (`lib/flash`), not a query param, so
// a reload of the landing page never replays the toast.
const setOutcome = (
c: Context,
- outcome: { connected: string } | { error: string },
+ outcome:
+ | { connected: string }
+ | { adminConsent: string }
+ | { error: string; integrationId: string },
) => {
- setCookie(
- c,
- flashCookieName(OAUTH_FLASH_KEY),
- "connected" in outcome
- ? `connected:${outcome.connected}`
- : `error:${outcome.error}`,
- {
- httpOnly: false,
- secure: cookieOptions.secure,
- sameSite: "lax",
- maxAge: FLASH_MAX_AGE,
- path: "/",
- },
- );
+ let value: string;
+ if ("connected" in outcome) {
+ value = `connected:${outcome.connected}`;
+ } else if ("adminConsent" in outcome) {
+ value = `admin_consent:${outcome.adminConsent}`;
+ } else {
+ value = `error:${outcome.error}:${outcome.integrationId}`;
+ }
+ setCookie(c, flashCookieName(OAUTH_FLASH_KEY), value, {
+ httpOnly: false,
+ secure: cookieOptions.secure,
+ sameSite: "lax",
+ maxAge: FLASH_MAX_AGE,
+ path: "/",
+ });
};
const app = new Hono().basePath(basePath);
@@ -75,6 +83,7 @@ export function OAuthIntegration<T extends string>(
const integration = await getIntegration({
integrationId: id as T,
callbackUrl: absoluteUrl(`${basePath}/callback/${id}`),
+ flow: "connect",
});
if (!integration) {
@@ -90,6 +99,8 @@ export function OAuthIntegration<T extends string>(
codeVerifier,
);
+ deleteCookie(c, ADMIN_CONSENT, { path: "/" });
+
// Set secure cookies
setCookie(c, STATE, state, {
httpOnly: true,
@@ -123,17 +134,74 @@ export function OAuthIntegration<T extends string>(
}
});
+ // A link a user hands to their administrator when their organization does
+ // not let users approve apps themselves. It carries no session: the
+ // administrator need not have a Rallly account.
+ app.get("/admin-consent/:id", validateParams, async (c) => {
+ try {
+ const { id } = c.req.valid("param");
+
+ const integration = await getIntegration({
+ integrationId: id as T,
+ callbackUrl: absoluteUrl(`${basePath}/callback/${id}`),
+ flow: "admin_consent",
+ });
+
+ if (!integration?.getAdminConsentUrl) {
+ return c.json({ error: `${id} does not support admin consent` }, 404);
+ }
+
+ const state = generateState();
+ const redirectTo = validateRedirectUrl(c.req.query("redirect")) || "/";
+
+ setCookie(c, STATE, state, {
+ httpOnly: true,
+ secure: cookieOptions.secure,
+ sameSite: cookieOptions.sameSite,
+ maxAge: cookieOptions.maxAge,
+ path: "/",
+ });
+
+ setCookie(c, REDIRECT_TO, redirectTo, {
+ httpOnly: true,
+ secure: cookieOptions.secure,
+ sameSite: cookieOptions.sameSite,
+ maxAge: cookieOptions.maxAge,
+ path: "/",
+ });
+
+ setCookie(c, ADMIN_CONSENT, id, {
+ httpOnly: true,
+ secure: cookieOptions.secure,
+ sameSite: cookieOptions.sameSite,
+ maxAge: cookieOptions.maxAge,
+ path: "/",
+ });
+
+ return c.redirect(integration.getAdminConsentUrl(state).toString());
+ } catch (error) {
+ logger.error({ error }, "Admin consent initiation failed");
+
+ return c.json({ error: "Failed to initiate admin consent" }, 404);
+ }
+ });
+
// OAuth callback endpoint
app.get("/callback/:id", validateParams, async (c) => {
try {
const { id } = c.req.valid("param");
+ const isAdminConsentGranted =
+ c.req.query("admin_consent")?.toLowerCase() === "true";
+ const isAdminConsent =
+ isAdminConsentGranted || getCookie(c, ADMIN_CONSENT) === id;
const integration = await getIntegration({
integrationId: id as T,
callbackUrl: absoluteUrl(`${basePath}/callback/${id}`),
+ flow: isAdminConsent ? "admin_consent" : "connect",
});
- if (!integration) {
+ if (!integration || (isAdminConsent && !integration.getAdminConsentUrl)) {
return c.json({ error: `${id} integration not configured` }, 404);
}
@@ -145,6 +213,20 @@ export function OAuthIntegration<T extends string>(
const redirectTo = validateRedirectUrl(storedRedirect) || "/";
+ // The return leg of an admin consent grant carries no code; the
+ // administrator's own sign in was never meant to create a connection.
+ if (isAdminConsent) {
+ deleteCookie(c, ADMIN_CONSENT, { path: "/" });
+ if (!state || !storedState || state !== storedState) {
+ setOutcome(c, { error: "invalid_request", integrationId: id });
+ } else if (isAdminConsentGranted) {
+ setOutcome(c, { adminConsent: id });
+ } else {
+ setOutcome(c, { error: "admin_consent_denied", integrationId: id });
+ }
+ return c.redirect(new URL(redirectTo, absoluteUrl()).toString());
+ }
+
// Validate OAuth callback parameters
if (
!code ||
@@ -153,7 +235,7 @@ export function OAuthIntegration<T extends string>(
state !== storedState ||
!codeVerifier
) {
- setOutcome(c, { error: "invalid_request" });
+ setOutcome(c, { error: "invalid_request", integrationId: id });
return c.redirect(new URL(redirectTo, absoluteUrl()).toString());
}
@@ -175,7 +257,10 @@ export function OAuthIntegration<T extends string>(
logger.error({ error }, "OAuth connection failed");
const redirectTo = getCookie(c, REDIRECT_TO) || "/";
- setOutcome(c, { error: "connection_failed" });
+ setOutcome(c, {
+ error: "connection_failed",
+ integrationId: c.req.param("id") ?? "",
+ });
return c.redirect(new URL(redirectTo, absoluteUrl()).toString());
}
});
diff --git a/apps/web/src/lib/oauth/types.ts b/apps/web/src/lib/oauth/types.ts
index 6740afbfc..dac0d24c2 100644
--- a/apps/web/src/lib/oauth/types.ts
+++ b/apps/web/src/lib/oauth/types.ts
@@ -38,6 +38,9 @@ export interface OAuthClient {
exchangeCode: (code: string, codeVerifier: string) => Promise<OAuthTokens>;
getUserInfo: (tokens: OAuthTokens) => Promise<UserInfo>;
refreshAccessToken: (refreshToken: string) => Promise<OAuthTokens>;
+ // For providers whose organizations can require an administrator to
+ // approve the app before their users may connect it.
+ getAdminConsentUrl?: (state: string) => URL;
}
export interface CreateOAuthOptions<T extends string> {
@@ -45,9 +48,13 @@ export interface CreateOAuthOptions<T extends string> {
getIntegration: ({
integrationId,
callbackUrl,
+ flow,
}: {
integrationId: T;
callbackUrl: string;
+ // `admin_consent` runs for an administrator who may have no Rallly
+ // session, so per user gates must not apply to it.
+ flow: "connect" | "admin_consent";
}) => OAuthClient | null | Promise<OAuthClient | null>;
cookieConfig?: {
prefix?: string;
diff --git a/packages/database/prisma/models/poll.prisma b/packages/database/prisma/models/poll.prisma
index 8362efbcc..6c6058873 100644
--- a/packages/database/prisma/models/poll.prisma
+++ b/packages/database/prisma/models/poll.prisma
@@ -38,7 +38,7 @@ model Poll {
description String?
location String?
/// What the organizer asked for: a provider to mint a link with at
- /// finalize ("zoom" | "meet"), or a link they pasted themselves.
+ /// finalize ("zoom" | "meet" | "teams"), or a link they pasted themselves.
conferencing Json?
userId String? @map("user_id")
timeZone String? @map("time_zone")