feat(automations): Microsoft Teams trigger provider
Merged
SA
3mo ago+2550+2550+0123456789012345678901234567890123456789-4-4-0123456789
What
Adds microsoft_teams as a trigger provider for automations, following the additive seam from #6571. Enum values are already on main (#6581) — no migration.
Events (fixed list from the brief):
| event | sentence |
|---|---|
message_in_channel | [Any message / containing "…"] in team › channel by Anyone/Me |
channel_created | Channel created in team [name contains "…"] |
Shape — Google-shaped, fetch-on-notify
- Connection = tenant admin consent, not a user sign-in.
connectredirects to Entra'sorganizations/v2.0/adminconsentwith.default;callbackproves consent by acquiring an app-only client-credentials token for the returned tenant (thetenantparam alone is attacker-controlled), upsertsintegration_connections(externalOrgId= tenant id, token cached with expiry,config={tenantId, clientState, subscriptions}), creates the Graph subscriptions, then chains an OpenID auth-code sign-in (identity/callback) so the consenting admin's Entraoidlands inuser_identities(providermicrosoft_teams,externalScopeId= tenant) — that is whatmeresolves through. Declining that leg costs only "Me", not the connection. - Subscriptions: two tenant-wide per connection —
/teams/getAllMessagesand/teams/getAllChannels,changeType: created,includeResourceData: false(no encryption certificate). Requested for 2 days (Graph allows 3 for these), renewed once within 12h byPOST /api/integrations/microsoft-teams/jobs/renew-subscriptions(QStash-signed, same pattern asautomations/evaluate). All subscription writes go through the per-connection advisory lock. - Notify + lifecycle routes answer inside Graph's 3-second window: echo
?validationToken=astext/plain; otherwise parse the collection, look up the connection by tenant, compareclientStatewithtimingSafeEqual(the only auth Graph offers without resource data), enqueue each accepted notification to QStash (deduped on subscription + changeType + resource), and answer 202. Refused notifications are acknowledged too — they will not verify on retry either. - Process route (
/api/integrations/microsoft-teams/process, QStash-signed) does the slow half: re-reads the connection and re-checks clientState, GETs the chatMessage / channel from Graph, records it inautomation_events(idempotent on connection + channel + message id; payload is the fetched resource) and dispatches throughtriggerMatches. For lifecycle items (reauthorizationRequired/subscriptionRemoved) it forces the renew/recreate step. Non-2xx → QStash retries. System messages (messageType != "message", e.g. "X added Y") are skipped. - Matcher
automation-matching/microsoft-teams.ts+ onecase:nullteam/channel scope matches nothing;channel_createdignores channel + actor (its sentence has neither);messageFilteris substring over the message text (HTML stripped) or the new channel's name.MatchContext.microsoftTeams = {teamId, channelId, ownerIds}. - Desktop:
providers/microsoftTeams/(grammar, renderer,useTeamsOptions→integration.microsoftTeams.listTeams/listChannels, channels labelled "Team › Channel"), one registry line, oneuseProviderOptionsline. ActorChip offers Anyone/Me only — the shared people list is GitHub ids. (Option keys will move to the provider-namespaced shape once the consolidated seam lands.) - Web:
/integrations/microsoft-teamspage (copy of Slack's) with Connect/Disconnect and subscription state; card on/integrations.
Prerequisites (documented, not yet provisioned)
- Entra app registration, multi-tenant, with application permissions
ChannelMessage.Read.All,Channel.ReadBasic.All,Team.ReadBasic.All(Organization.Read.Alloptional — only the tenant display name). Redirect URIs:{API}/api/integrations/microsoft-teams/callbackand{API}/api/integrations/microsoft-teams/identity/callback. MICROSOFT_CLIENT_ID/MICROSOFT_CLIENT_SECRETin api + trpc env (both optional — unset means the integration is off and nothing else changes).- App-only channel-message reads are a Microsoft protected API: Graph 403s subscription create until the app id is approved via Microsoft's request form.
- A QStash schedule hitting
/api/integrations/microsoft-teams/jobs/renew-subscriptionshourly. /teams/getAllMessagesis subscribed without?model=→ Graph evaluation mode, capped at 500 messages / app / tenant / month. Flipping to model A (E5 licences) or B (per-message billing) is one constant insubscriptions.ts.
Verification
- typecheck 0: shared, db, trpc, api, desktop, web. Lint: clean except the pre-existing
TerminalAgentAutoResumea11y failure on main. - Desktop over CDP (this worktree's renderer, vite :8865, api :8861): Add Trigger → Microsoft Teams → both events; Save with empty scopes refused with team/channel chips marked; configured (Any team › Any channel, filter "deploy"; Channel created in Any team, "incident"), saved, persisted across a full reload; DB rows carry the expected config.
- Notify route:
?validationToken=abc%20123%2Bxyz→ 200text/plainabc 123+xyz(lifecycle route too); bad JSON 400; unknown tenant refused; wrongclientStaterefused; correctclientStateaccepted (before the queue split, the same request reached the real Graph GET and got the expected 401 on a placeholder token; with the queue, QStash rejects loopback URLs locally, as it does for every other automation route). - Ingest (
ingestChannelMessage/ingestChannel, what the process route calls after the Graph GET) with Graph-shaped chatMessage / channel payloads against the real DB: rows recorded with title/url/actor/resourceKey, redelivery deduped, matcher selects 1/2 triggers for a "deploy" message and 1/2 for an "incident-…" channel, 0/2 for non-matching. - Not verified live: consent flow, identity leg, subscription create/renew, and a real Graph push — need the tenant + protected-API approval above.