feat(automations): Microsoft Teams trigger provider

Merged
SA
3mo ago
+2550-4

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):

eventsentence
message_in_channel[Any message / containing "…"] in team › channel by Anyone/Me
channel_createdChannel created in team [name contains "…"]

Shape — Google-shaped, fetch-on-notify

  • Connection = tenant admin consent, not a user sign-in. connect redirects to Entra's organizations/v2.0/adminconsent with .default; callback proves consent by acquiring an app-only client-credentials token for the returned tenant (the tenant param alone is attacker-controlled), upserts integration_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 Entra oid lands in user_identities (provider microsoft_teams, externalScopeId = tenant) — that is what me resolves through. Declining that leg costs only "Me", not the connection.
  • Subscriptions: two tenant-wide per connection — /teams/getAllMessages and /teams/getAllChannels, changeType: created, includeResourceData: false (no encryption certificate). Requested for 2 days (Graph allows 3 for these), renewed once within 12h by POST /api/integrations/microsoft-teams/jobs/renew-subscriptions (QStash-signed, same pattern as automations/evaluate). All subscription writes go through the per-connection advisory lock.
  • Notify + lifecycle routes answer inside Graph's 3-second window: echo ?validationToken= as text/plain; otherwise parse the collection, look up the connection by tenant, compare clientState with timingSafeEqual (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 in automation_events (idempotent on connection + channel + message id; payload is the fetched resource) and dispatches through triggerMatches. 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 + one case: null team/channel scope matches nothing; channel_created ignores channel + actor (its sentence has neither); messageFilter is 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, one useProviderOptions line. 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-teams page (copy of Slack's) with Connect/Disconnect and subscription state; card on /integrations.

Prerequisites (documented, not yet provisioned)

  1. Entra app registration, multi-tenant, with application permissions ChannelMessage.Read.All, Channel.ReadBasic.All, Team.ReadBasic.All (Organization.Read.All optional — only the tenant display name). Redirect URIs: {API}/api/integrations/microsoft-teams/callback and {API}/api/integrations/microsoft-teams/identity/callback.
  2. MICROSOFT_CLIENT_ID / MICROSOFT_CLIENT_SECRET in api + trpc env (both optional — unset means the integration is off and nothing else changes).
  3. 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.
  4. A QStash schedule hitting /api/integrations/microsoft-teams/jobs/renew-subscriptions hourly.
  5. /teams/getAllMessages is 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 in subscriptions.ts.

Verification

  • typecheck 0: shared, db, trpc, api, desktop, web. Lint: clean except the pre-existing TerminalAgentAutoResume a11y 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 → 200 text/plain abc 123+xyz (lifecycle route too); bad JSON 400; unknown tenant refused; wrong clientState refused; correct clientState accepted (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.