@gakr-gakr/msteams 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/api.ts +3 -0
  2. package/autobot.plugin.json +15 -0
  3. package/channel-config-api.ts +1 -0
  4. package/channel-plugin-api.ts +2 -0
  5. package/config-api.ts +4 -0
  6. package/contract-api.ts +4 -0
  7. package/index.ts +20 -0
  8. package/package.json +72 -0
  9. package/runtime-api.ts +66 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.ts +348 -0
  16. package/src/attachments/download.ts +328 -0
  17. package/src/attachments/graph.ts +489 -0
  18. package/src/attachments/html.ts +122 -0
  19. package/src/attachments/payload.ts +14 -0
  20. package/src/attachments/remote-media.ts +86 -0
  21. package/src/attachments/shared.ts +655 -0
  22. package/src/attachments/types.ts +47 -0
  23. package/src/attachments.ts +18 -0
  24. package/src/channel-api.ts +1 -0
  25. package/src/channel.runtime.ts +56 -0
  26. package/src/channel.setup.ts +77 -0
  27. package/src/channel.ts +1176 -0
  28. package/src/config-schema.ts +6 -0
  29. package/src/config-ui-hints.ts +40 -0
  30. package/src/conversation-store-fs.ts +149 -0
  31. package/src/conversation-store-helpers.ts +105 -0
  32. package/src/conversation-store-memory.ts +51 -0
  33. package/src/conversation-store.ts +71 -0
  34. package/src/directory-live.ts +111 -0
  35. package/src/doctor.ts +27 -0
  36. package/src/errors.ts +270 -0
  37. package/src/feedback-reflection-prompt.ts +117 -0
  38. package/src/feedback-reflection-store.ts +113 -0
  39. package/src/feedback-reflection.ts +271 -0
  40. package/src/file-consent-helpers.ts +115 -0
  41. package/src/file-consent-invoke.ts +150 -0
  42. package/src/file-consent.ts +223 -0
  43. package/src/graph-chat.ts +36 -0
  44. package/src/graph-group-management.ts +168 -0
  45. package/src/graph-members.ts +48 -0
  46. package/src/graph-messages.ts +534 -0
  47. package/src/graph-teams.ts +114 -0
  48. package/src/graph-thread.ts +146 -0
  49. package/src/graph-upload.ts +531 -0
  50. package/src/graph-users.ts +29 -0
  51. package/src/graph.ts +308 -0
  52. package/src/inbound.ts +148 -0
  53. package/src/index.ts +4 -0
  54. package/src/media-helpers.ts +105 -0
  55. package/src/mentions.ts +114 -0
  56. package/src/messenger.ts +608 -0
  57. package/src/monitor-handler/access.ts +136 -0
  58. package/src/monitor-handler/inbound-media.ts +180 -0
  59. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  60. package/src/monitor-handler/message-handler.test-support.ts +102 -0
  61. package/src/monitor-handler/message-handler.ts +1015 -0
  62. package/src/monitor-handler/reaction-handler.ts +124 -0
  63. package/src/monitor-handler/thread-session.ts +30 -0
  64. package/src/monitor-handler.ts +538 -0
  65. package/src/monitor-handler.types.ts +27 -0
  66. package/src/monitor-types.ts +6 -0
  67. package/src/monitor.ts +476 -0
  68. package/src/oauth.flow.ts +77 -0
  69. package/src/oauth.shared.ts +37 -0
  70. package/src/oauth.token.ts +162 -0
  71. package/src/oauth.ts +130 -0
  72. package/src/outbound.ts +198 -0
  73. package/src/pending-uploads-fs.ts +235 -0
  74. package/src/pending-uploads.ts +121 -0
  75. package/src/policy.ts +245 -0
  76. package/src/polls-store-memory.ts +32 -0
  77. package/src/polls.ts +312 -0
  78. package/src/presentation.ts +93 -0
  79. package/src/probe.ts +132 -0
  80. package/src/reply-dispatcher.ts +523 -0
  81. package/src/reply-stream-controller.ts +334 -0
  82. package/src/resolve-allowlist.ts +309 -0
  83. package/src/revoked-context.ts +17 -0
  84. package/src/runtime.ts +12 -0
  85. package/src/sdk-types.ts +59 -0
  86. package/src/sdk.ts +916 -0
  87. package/src/secret-contract.ts +49 -0
  88. package/src/secret-input.ts +7 -0
  89. package/src/send-context.ts +269 -0
  90. package/src/send.ts +697 -0
  91. package/src/sent-message-cache.ts +174 -0
  92. package/src/session-route.ts +40 -0
  93. package/src/setup-core.ts +162 -0
  94. package/src/setup-surface.ts +319 -0
  95. package/src/sso-token-store.ts +166 -0
  96. package/src/sso.ts +300 -0
  97. package/src/storage.ts +25 -0
  98. package/src/store-fs.ts +42 -0
  99. package/src/streaming-message.ts +327 -0
  100. package/src/thread-parent-context.ts +159 -0
  101. package/src/token-response.ts +11 -0
  102. package/src/token.ts +194 -0
  103. package/src/user-agent.ts +53 -0
  104. package/src/webhook-timeouts.ts +27 -0
  105. package/src/welcome-card.ts +57 -0
  106. package/test-api.ts +1 -0
  107. package/tsconfig.json +16 -0
@@ -0,0 +1,27 @@
1
+ import { type AutoBotConfig, type RuntimeEnv } from "../runtime-api.js";
2
+ import type { MSTeamsConversationStore } from "./conversation-store.js";
3
+ import type { MSTeamsAdapter } from "./messenger.js";
4
+ import type { MSTeamsMonitorLogger } from "./monitor-types.js";
5
+ import type { MSTeamsPollStore } from "./polls.js";
6
+ import type { MSTeamsSsoDeps } from "./sso.js";
7
+
8
+ export type MSTeamsMessageHandlerDeps = {
9
+ cfg: AutoBotConfig;
10
+ runtime: RuntimeEnv;
11
+ appId: string;
12
+ adapter: MSTeamsAdapter;
13
+ tokenProvider: {
14
+ getAccessToken: (scope: string) => Promise<string>;
15
+ };
16
+ textLimit: number;
17
+ mediaMaxBytes: number;
18
+ conversationStore: MSTeamsConversationStore;
19
+ pollStore: MSTeamsPollStore;
20
+ log: MSTeamsMonitorLogger;
21
+ /**
22
+ * Optional Bot Framework OAuth SSO deps. When omitted the plugin
23
+ * does not handle `signin/tokenExchange` or `signin/verifyState`
24
+ * invokes, matching the pre-SSO behavior.
25
+ */
26
+ sso?: MSTeamsSsoDeps;
27
+ };
@@ -0,0 +1,6 @@
1
+ export type MSTeamsMonitorLogger = {
2
+ debug?: (message: string, meta?: Record<string, unknown>) => void;
3
+ info: (message: string, meta?: Record<string, unknown>) => void;
4
+ warn?: (message: string, meta?: Record<string, unknown>) => void;
5
+ error: (message: string, meta?: Record<string, unknown>) => void;
6
+ };
package/src/monitor.ts ADDED
@@ -0,0 +1,476 @@
1
+ import type { Request, Response } from "express";
2
+ import {
3
+ DEFAULT_WEBHOOK_MAX_BODY_BYTES,
4
+ isDangerousNameMatchingEnabled,
5
+ keepHttpServerTaskAlive,
6
+ mergeAllowlist,
7
+ summarizeMapping,
8
+ type AutoBotConfig,
9
+ type RuntimeEnv,
10
+ } from "../runtime-api.js";
11
+ import { createMSTeamsConversationStoreFs } from "./conversation-store-fs.js";
12
+ import type { MSTeamsConversationStore } from "./conversation-store.js";
13
+ import { formatUnknownError } from "./errors.js";
14
+ import type { MSTeamsAdapter } from "./messenger.js";
15
+ import { registerMSTeamsHandlers, type MSTeamsActivityHandler } from "./monitor-handler.js";
16
+ import { createMSTeamsPollStoreFs, type MSTeamsPollStore } from "./polls.js";
17
+ import {
18
+ resolveMSTeamsChannelAllowlist,
19
+ resolveMSTeamsUserAllowlist,
20
+ } from "./resolve-allowlist.js";
21
+ import { getMSTeamsRuntime } from "./runtime.js";
22
+ import {
23
+ createBotFrameworkJwtValidator,
24
+ createMSTeamsAdapter,
25
+ createMSTeamsTokenProvider,
26
+ loadMSTeamsSdkWithAuth,
27
+ } from "./sdk.js";
28
+ import { createMSTeamsSsoTokenStoreFs } from "./sso-token-store.js";
29
+ import type { MSTeamsSsoDeps } from "./sso.js";
30
+ import { resolveMSTeamsCredentials } from "./token.js";
31
+ import { applyMSTeamsWebhookTimeouts } from "./webhook-timeouts.js";
32
+
33
+ type MonitorMSTeamsOpts = {
34
+ cfg: AutoBotConfig;
35
+ runtime?: RuntimeEnv;
36
+ abortSignal?: AbortSignal;
37
+ conversationStore?: MSTeamsConversationStore;
38
+ pollStore?: MSTeamsPollStore;
39
+ };
40
+
41
+ type MonitorMSTeamsResult = {
42
+ app: unknown;
43
+ shutdown: () => Promise<void>;
44
+ };
45
+
46
+ const MSTEAMS_WEBHOOK_MAX_BODY_BYTES = DEFAULT_WEBHOOK_MAX_BODY_BYTES;
47
+ export async function monitorMSTeamsProvider(
48
+ opts: MonitorMSTeamsOpts,
49
+ ): Promise<MonitorMSTeamsResult> {
50
+ const core = getMSTeamsRuntime();
51
+ const log = core.logging.getChildLogger({ name: "msteams" });
52
+ let cfg = opts.cfg;
53
+ let msteamsCfg = cfg.channels?.msteams;
54
+ if (!msteamsCfg?.enabled) {
55
+ log.debug?.("msteams provider disabled");
56
+ return { app: null, shutdown: async () => {} };
57
+ }
58
+
59
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
60
+ if (!creds) {
61
+ log.error("msteams credentials not configured");
62
+ return { app: null, shutdown: async () => {} };
63
+ }
64
+ const appId = creds.appId; // Extract for use in closures
65
+
66
+ const runtime: RuntimeEnv = opts.runtime ?? {
67
+ log: console.log,
68
+ error: console.error,
69
+ exit: (code: number): never => {
70
+ throw new Error(`exit ${code}`);
71
+ },
72
+ };
73
+
74
+ let allowFrom = msteamsCfg.allowFrom;
75
+ let groupAllowFrom = msteamsCfg.groupAllowFrom;
76
+ let teamsConfig = msteamsCfg.teams;
77
+ const allowNameMatching = isDangerousNameMatchingEnabled(msteamsCfg);
78
+
79
+ const cleanAllowEntry = (entry: string) =>
80
+ entry
81
+ .replace(/^(msteams|teams):/i, "")
82
+ .replace(/^user:/i, "")
83
+ .trim();
84
+ const isStableUserId = (entry: string) => /^[0-9a-fA-F-]{16,}$/.test(entry);
85
+ const cleanAllowEntries = (entries?: string[]) =>
86
+ entries?.map((entry) => cleanAllowEntry(entry)).filter((entry) => entry && entry !== "*") ?? [];
87
+ const mergeStableUserIds = (entries?: string[]) => {
88
+ const additions = cleanAllowEntries(entries).filter((entry) => isStableUserId(entry));
89
+ return additions.length > 0 ? mergeAllowlist({ existing: entries, additions }) : entries;
90
+ };
91
+
92
+ const resolveAllowlistUsers = async (label: string, entries: string[]) => {
93
+ if (entries.length === 0) {
94
+ return { additions: [], unresolved: [] };
95
+ }
96
+ const resolved = await resolveMSTeamsUserAllowlist({ cfg, entries });
97
+ const additions: string[] = [];
98
+ const unresolved: string[] = [];
99
+ for (const entry of resolved) {
100
+ if (entry.resolved && entry.id) {
101
+ additions.push(entry.id);
102
+ } else {
103
+ unresolved.push(entry.input);
104
+ }
105
+ }
106
+ const mapping = resolved
107
+ .filter((entry) => entry.resolved && entry.id)
108
+ .map((entry) => `${entry.input}→${entry.id}`);
109
+ summarizeMapping(label, mapping, unresolved, runtime);
110
+ return { additions, unresolved };
111
+ };
112
+
113
+ try {
114
+ allowFrom = mergeStableUserIds(allowFrom);
115
+ if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) {
116
+ groupAllowFrom = mergeStableUserIds(groupAllowFrom);
117
+ }
118
+
119
+ if (allowNameMatching) {
120
+ const allowEntries = cleanAllowEntries(allowFrom).filter((entry) => !isStableUserId(entry));
121
+ if (allowEntries.length > 0) {
122
+ const { additions } = await resolveAllowlistUsers("msteams users", allowEntries);
123
+ allowFrom = mergeAllowlist({ existing: allowFrom, additions });
124
+ }
125
+
126
+ if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) {
127
+ const groupEntries = cleanAllowEntries(groupAllowFrom).filter(
128
+ (entry) => !isStableUserId(entry),
129
+ );
130
+ if (groupEntries.length > 0) {
131
+ const { additions } = await resolveAllowlistUsers("msteams group users", groupEntries);
132
+ groupAllowFrom = mergeAllowlist({ existing: groupAllowFrom, additions });
133
+ }
134
+ }
135
+ }
136
+
137
+ if (teamsConfig && Object.keys(teamsConfig).length > 0) {
138
+ const entries: Array<{ input: string; teamKey: string; channelKey?: string }> = [];
139
+ for (const [teamKey, teamCfg] of Object.entries(teamsConfig)) {
140
+ if (teamKey === "*") {
141
+ continue;
142
+ }
143
+ const channels = teamCfg?.channels ?? {};
144
+ const channelKeys = Object.keys(channels).filter((key) => key !== "*");
145
+ if (channelKeys.length === 0) {
146
+ entries.push({ input: teamKey, teamKey });
147
+ continue;
148
+ }
149
+ for (const channelKey of channelKeys) {
150
+ entries.push({
151
+ input: `${teamKey}/${channelKey}`,
152
+ teamKey,
153
+ channelKey,
154
+ });
155
+ }
156
+ }
157
+
158
+ if (entries.length > 0) {
159
+ const resolved = await resolveMSTeamsChannelAllowlist({
160
+ cfg,
161
+ entries: entries.map((entry) => entry.input),
162
+ });
163
+ const mapping: string[] = [];
164
+ const unresolved: string[] = [];
165
+ const nextTeams = { ...teamsConfig };
166
+
167
+ resolved.forEach((entry, idx) => {
168
+ const source = entries[idx];
169
+ if (!source) {
170
+ return;
171
+ }
172
+ const sourceTeam = teamsConfig?.[source.teamKey] ?? {};
173
+ if (!entry.resolved || !entry.teamId) {
174
+ unresolved.push(entry.input);
175
+ return;
176
+ }
177
+ mapping.push(
178
+ entry.channelId
179
+ ? `${entry.input}→${entry.teamId}/${entry.channelId}`
180
+ : `${entry.input}→${entry.teamId}`,
181
+ );
182
+ const existing = nextTeams[entry.teamId] ?? {};
183
+ const mergedChannels = {
184
+ ...sourceTeam.channels,
185
+ ...existing.channels,
186
+ };
187
+ const mergedTeam = { ...sourceTeam, ...existing, channels: mergedChannels };
188
+ nextTeams[entry.teamId] = mergedTeam;
189
+ if (source.channelKey && entry.channelId) {
190
+ const sourceChannel = sourceTeam.channels?.[source.channelKey];
191
+ if (sourceChannel) {
192
+ nextTeams[entry.teamId] = {
193
+ ...mergedTeam,
194
+ channels: {
195
+ ...mergedChannels,
196
+ [entry.channelId]: {
197
+ ...sourceChannel,
198
+ ...mergedChannels?.[entry.channelId],
199
+ },
200
+ },
201
+ };
202
+ }
203
+ }
204
+ });
205
+
206
+ teamsConfig = nextTeams;
207
+ summarizeMapping("msteams channels", mapping, unresolved, runtime);
208
+ }
209
+ }
210
+ } catch (err) {
211
+ // Log at error (not log) — allowlist resolution failures leave the bot in a
212
+ // degraded state where Graph-resolved IDs are missing (#77674).
213
+ runtime?.error(
214
+ `msteams resolve failed; falling back to raw config entries — allowlist members resolved via Graph may be missing. ${formatUnknownError(err)}`,
215
+ );
216
+ }
217
+
218
+ msteamsCfg = {
219
+ ...msteamsCfg,
220
+ allowFrom,
221
+ groupAllowFrom,
222
+ teams: teamsConfig,
223
+ };
224
+ cfg = {
225
+ ...cfg,
226
+ channels: {
227
+ ...cfg.channels,
228
+ msteams: msteamsCfg,
229
+ },
230
+ };
231
+
232
+ const port = msteamsCfg.webhook?.port ?? 3978;
233
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "msteams");
234
+ const MB = 1024 * 1024;
235
+ const agentDefaults = cfg.agents?.defaults;
236
+ const mediaMaxBytes =
237
+ typeof agentDefaults?.mediaMaxMb === "number" && agentDefaults.mediaMaxMb > 0
238
+ ? Math.floor(agentDefaults.mediaMaxMb * MB)
239
+ : 8 * MB;
240
+ const conversationStore = opts.conversationStore ?? createMSTeamsConversationStoreFs();
241
+ const pollStore = opts.pollStore ?? createMSTeamsPollStoreFs();
242
+
243
+ log.info(`starting provider (port ${port})`);
244
+
245
+ // Dynamic import to avoid loading SDK when provider is disabled
246
+ const express = await import("express");
247
+
248
+ const { sdk, app } = await loadMSTeamsSdkWithAuth(creds);
249
+
250
+ // Build a token provider adapter for Graph API operations
251
+ const tokenProvider = createMSTeamsTokenProvider(app);
252
+
253
+ const adapter = createMSTeamsAdapter(app, sdk);
254
+
255
+ // Build SSO deps when the operator has opted in and a connection name
256
+ // is configured. Leaving `sso` undefined matches the pre-SSO behavior
257
+ // (the plugin will still ack signin invokes, but will not attempt a
258
+ // Bot Framework token exchange or persist anything).
259
+ let ssoDeps: MSTeamsSsoDeps | undefined;
260
+ if (msteamsCfg.sso?.enabled && msteamsCfg.sso.connectionName) {
261
+ ssoDeps = {
262
+ tokenProvider,
263
+ tokenStore: createMSTeamsSsoTokenStoreFs(),
264
+ connectionName: msteamsCfg.sso.connectionName,
265
+ };
266
+ log.debug?.("msteams sso enabled", {
267
+ connectionName: msteamsCfg.sso.connectionName,
268
+ });
269
+ }
270
+
271
+ // Build a simple ActivityHandler-compatible object
272
+ const handler = buildActivityHandler();
273
+ registerMSTeamsHandlers(handler, {
274
+ cfg,
275
+ runtime,
276
+ appId,
277
+ adapter: adapter as unknown as MSTeamsAdapter,
278
+ tokenProvider,
279
+ textLimit,
280
+ mediaMaxBytes,
281
+ conversationStore,
282
+ pollStore,
283
+ log,
284
+ sso: ssoDeps,
285
+ });
286
+
287
+ // Create Express server
288
+ const expressApp = express.default();
289
+
290
+ // Cheap pre-parse auth gate: reject requests without a Bearer token before
291
+ // spending CPU/memory on JSON body parsing. This prevents unauthenticated
292
+ // request floods from forcing body parsing on internet-exposed webhooks.
293
+ expressApp.use((req: Request, res: Response, next: (err?: unknown) => void) => {
294
+ const auth = req.headers.authorization;
295
+ if (!auth || !auth.startsWith("Bearer ")) {
296
+ res.status(401).json({ error: "Unauthorized" });
297
+ return;
298
+ }
299
+ next();
300
+ });
301
+
302
+ // JWT validation — verify Bot Framework tokens using the Teams SDK's
303
+ // JwtValidator (validates signature via JWKS, audience, issuer, expiration).
304
+ const jwtValidator = await createBotFrameworkJwtValidator(creds);
305
+ expressApp.use((req: Request, res: Response, next: (err?: unknown) => void) => {
306
+ // Authorization header is guaranteed by the pre-parse auth gate above.
307
+ // `serviceUrl` is optional, so authenticate from headers alone before body
308
+ // I/O to avoid spending memory and CPU on unauthenticated requests.
309
+ const authHeader = req.headers.authorization!;
310
+ jwtValidator
311
+ .validate(authHeader)
312
+ .then((valid) => {
313
+ if (!valid) {
314
+ log.debug?.("JWT validation failed");
315
+ res.status(401).json({ error: "Unauthorized" });
316
+ return;
317
+ }
318
+ next();
319
+ })
320
+ .catch((err) => {
321
+ // Network-level failures (DNS, firewall, TLS toward login.botframework.com)
322
+ // are rethrown by the validator so we can log them visibly. Without this,
323
+ // they look identical to a bad credential at default log levels (#77674).
324
+ const isNetworkFailure =
325
+ err instanceof Error &&
326
+ /ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT|ECONNRESET/i.test(
327
+ (err as NodeJS.ErrnoException).code ?? err.message,
328
+ );
329
+ if (isNetworkFailure) {
330
+ // Network failure fetching JWKS keys — log visibly so operators can
331
+ // identify egress blocks to login.botframework.com (#77674).
332
+ runtime?.error(
333
+ `msteams: JWKS key fetch failed — check egress to login.botframework.com:443 (firewall or DNS may be blocking it). Bot will 401 all inbound requests until this is resolved. Error: ${formatUnknownError(err)}`,
334
+ );
335
+ } else {
336
+ log.debug?.(`JWT validation error: ${formatUnknownError(err)}`);
337
+ }
338
+ res.status(401).json({ error: "Unauthorized" });
339
+ });
340
+ });
341
+
342
+ expressApp.use(express.json({ limit: MSTEAMS_WEBHOOK_MAX_BODY_BYTES }));
343
+ expressApp.use((err: unknown, _req: Request, res: Response, next: (err?: unknown) => void) => {
344
+ if (err && typeof err === "object" && "status" in err && err.status === 413) {
345
+ res.status(413).json({ error: "Payload too large" });
346
+ return;
347
+ }
348
+ next(err);
349
+ });
350
+
351
+ // Set up the messages endpoint - use configured path and /api/messages as fallback
352
+ const configuredPath = msteamsCfg.webhook?.path ?? "/api/messages";
353
+ const messageHandler = (req: Request, res: Response) => {
354
+ void adapter
355
+ .process(req, res, (context: unknown) => handler.run!(context))
356
+ .catch((err: unknown) => {
357
+ log.error("msteams webhook failed", { error: formatUnknownError(err) });
358
+ });
359
+ };
360
+
361
+ // Listen on configured path and /api/messages (standard Bot Framework path)
362
+ expressApp.post(configuredPath, messageHandler);
363
+ if (configuredPath !== "/api/messages") {
364
+ expressApp.post("/api/messages", messageHandler);
365
+ }
366
+
367
+ log.debug?.("listening on paths", {
368
+ primary: configuredPath,
369
+ fallback: "/api/messages",
370
+ });
371
+
372
+ // Start listening and fail fast if bind/listen fails.
373
+ const httpServer = expressApp.listen(port);
374
+ await new Promise<void>((resolve, reject) => {
375
+ const onListening = () => {
376
+ httpServer.off("error", onError);
377
+ log.info(`msteams provider started on port ${port}`);
378
+ resolve();
379
+ };
380
+ const onError = (err: unknown) => {
381
+ httpServer.off("listening", onListening);
382
+ log.error("msteams server error", { error: formatUnknownError(err) });
383
+ reject(err);
384
+ };
385
+ httpServer.once("listening", onListening);
386
+ httpServer.once("error", onError);
387
+ });
388
+ applyMSTeamsWebhookTimeouts(httpServer);
389
+
390
+ httpServer.on("error", (err) => {
391
+ log.error("msteams server error", { error: formatUnknownError(err) });
392
+ });
393
+
394
+ const shutdown = async () => {
395
+ log.info("shutting down msteams provider");
396
+ return new Promise<void>((resolve) => {
397
+ httpServer.close((err) => {
398
+ if (err) {
399
+ log.debug?.("msteams server close error", { error: formatUnknownError(err) });
400
+ }
401
+ resolve();
402
+ });
403
+ });
404
+ };
405
+
406
+ // Keep this task alive until close so gateway runtime does not treat startup as exit.
407
+ await keepHttpServerTaskAlive({
408
+ server: httpServer,
409
+ abortSignal: opts.abortSignal,
410
+ onAbort: shutdown,
411
+ });
412
+
413
+ return { app: expressApp, shutdown };
414
+ }
415
+
416
+ /**
417
+ * Build a minimal ActivityHandler-compatible object that supports
418
+ * onMessage / onMembersAdded registration and a run() method.
419
+ */
420
+ function buildActivityHandler(): MSTeamsActivityHandler {
421
+ type Handler = (context: unknown, next: () => Promise<void>) => Promise<void>;
422
+ const messageHandlers: Handler[] = [];
423
+ const membersAddedHandlers: Handler[] = [];
424
+ const reactionsAddedHandlers: Handler[] = [];
425
+ const reactionsRemovedHandlers: Handler[] = [];
426
+
427
+ const handler: MSTeamsActivityHandler = {
428
+ onMessage(cb) {
429
+ messageHandlers.push(cb);
430
+ return handler;
431
+ },
432
+ onMembersAdded(cb) {
433
+ membersAddedHandlers.push(cb);
434
+ return handler;
435
+ },
436
+ onReactionsAdded(cb) {
437
+ reactionsAddedHandlers.push(cb);
438
+ return handler;
439
+ },
440
+ onReactionsRemoved(cb) {
441
+ reactionsRemovedHandlers.push(cb);
442
+ return handler;
443
+ },
444
+ async run(context: unknown) {
445
+ const ctx = context as { activity?: { type?: string } };
446
+ const activityType = ctx?.activity?.type;
447
+ const noop = async () => {};
448
+
449
+ if (activityType === "message") {
450
+ for (const h of messageHandlers) {
451
+ await h(context, noop);
452
+ }
453
+ } else if (activityType === "conversationUpdate") {
454
+ for (const h of membersAddedHandlers) {
455
+ await h(context, noop);
456
+ }
457
+ } else if (activityType === "messageReaction") {
458
+ const activity = (
459
+ ctx as { activity?: { reactionsAdded?: unknown[]; reactionsRemoved?: unknown[] } }
460
+ )?.activity;
461
+ if (activity?.reactionsAdded?.length) {
462
+ for (const h of reactionsAddedHandlers) {
463
+ await h(context, noop);
464
+ }
465
+ }
466
+ if (activity?.reactionsRemoved?.length) {
467
+ for (const h of reactionsRemovedHandlers) {
468
+ await h(context, noop);
469
+ }
470
+ }
471
+ }
472
+ },
473
+ };
474
+
475
+ return handler;
476
+ }
@@ -0,0 +1,77 @@
1
+ import { generateHexPkceVerifierChallenge } from "autobot/plugin-sdk/provider-auth";
2
+ import {
3
+ generateOAuthState,
4
+ parseOAuthCallbackInput,
5
+ waitForLocalOAuthCallback,
6
+ } from "autobot/plugin-sdk/provider-auth-runtime";
7
+ import { isWSL2Sync } from "autobot/plugin-sdk/runtime-env";
8
+ import {
9
+ MSTEAMS_DEFAULT_DELEGATED_SCOPES,
10
+ MSTEAMS_OAUTH_CALLBACK_PATH,
11
+ MSTEAMS_OAUTH_CALLBACK_PORT,
12
+ MSTEAMS_OAUTH_REDIRECT_URI,
13
+ buildMSTeamsAuthEndpoint,
14
+ } from "./oauth.shared.js";
15
+
16
+ export function shouldUseManualOAuthFlow(isRemote: boolean): boolean {
17
+ return isRemote || isWSL2Sync();
18
+ }
19
+
20
+ export function generatePkce(): { verifier: string; challenge: string } {
21
+ return generateHexPkceVerifierChallenge();
22
+ }
23
+
24
+ export { generateOAuthState };
25
+
26
+ export function buildMSTeamsAuthUrl(params: {
27
+ tenantId: string;
28
+ clientId: string;
29
+ challenge: string;
30
+ /** Opaque CSRF state token — must NOT be the PKCE verifier. */
31
+ state: string;
32
+ scopes?: readonly string[];
33
+ }): string {
34
+ const scopes = params.scopes ?? MSTEAMS_DEFAULT_DELEGATED_SCOPES;
35
+ const endpoint = buildMSTeamsAuthEndpoint(params.tenantId);
36
+ const query = new URLSearchParams({
37
+ client_id: params.clientId,
38
+ response_type: "code",
39
+ redirect_uri: MSTEAMS_OAUTH_REDIRECT_URI,
40
+ scope: scopes.join(" "),
41
+ code_challenge: params.challenge,
42
+ code_challenge_method: "S256",
43
+ state: params.state,
44
+ prompt: "consent",
45
+ });
46
+ return `${endpoint}?${query.toString()}`;
47
+ }
48
+
49
+ export function parseCallbackInput(
50
+ input: string,
51
+ // Kept in the signature for API symmetry with the caller's CSRF verify step.
52
+ // The caller compares the parsed `state` against the expected value.
53
+ _expectedState: string,
54
+ ): { code: string; state: string } | { error: string } {
55
+ return parseOAuthCallbackInput(input, {
56
+ missingState: "Missing 'state' parameter in URL. Paste the full redirect URL.",
57
+ invalidInput:
58
+ "Paste the full redirect URL (including code and state parameters), not just the authorization code.",
59
+ });
60
+ }
61
+
62
+ export async function waitForLocalCallback(params: {
63
+ expectedState: string;
64
+ timeoutMs: number;
65
+ onProgress?: (message: string) => void;
66
+ }): Promise<{ code: string; state: string }> {
67
+ return await waitForLocalOAuthCallback({
68
+ expectedState: params.expectedState,
69
+ timeoutMs: params.timeoutMs,
70
+ port: MSTEAMS_OAUTH_CALLBACK_PORT,
71
+ callbackPath: MSTEAMS_OAUTH_CALLBACK_PATH,
72
+ redirectUri: MSTEAMS_OAUTH_REDIRECT_URI,
73
+ successTitle: "MSTeams Delegated OAuth complete",
74
+ progressMessage: `Waiting for OAuth callback on ${MSTEAMS_OAUTH_REDIRECT_URI}...`,
75
+ onProgress: params.onProgress,
76
+ });
77
+ }
@@ -0,0 +1,37 @@
1
+ export const MSTEAMS_OAUTH_REDIRECT_URI = "http://localhost:8086/oauth2callback";
2
+ export const MSTEAMS_OAUTH_CALLBACK_PORT = 8086;
3
+ export const MSTEAMS_OAUTH_CALLBACK_PATH = "/oauth2callback";
4
+ export const MSTEAMS_DEFAULT_TOKEN_FETCH_TIMEOUT_MS = 10_000;
5
+
6
+ export const MSTEAMS_DEFAULT_DELEGATED_SCOPES = [
7
+ "ChatMessage.Send",
8
+ "ChannelMessage.Send",
9
+ "Chat.ReadWrite",
10
+ "offline_access",
11
+ ] as const;
12
+
13
+ export function buildMSTeamsAuthEndpoint(tenantId: string): string {
14
+ return `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/authorize`;
15
+ }
16
+
17
+ export function buildMSTeamsTokenEndpoint(tenantId: string): string {
18
+ return `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`;
19
+ }
20
+
21
+ export type MSTeamsDelegatedTokens = {
22
+ accessToken: string;
23
+ refreshToken: string;
24
+ /** Unix ms, 5-min buffer pre-applied */
25
+ expiresAt: number;
26
+ scopes: string[];
27
+ userPrincipalName?: string;
28
+ };
29
+
30
+ export type MSTeamsDelegatedOAuthContext = {
31
+ isRemote: boolean;
32
+ openUrl: (url: string) => Promise<void>;
33
+ log: (msg: string) => void;
34
+ note: (message: string, title?: string) => Promise<void>;
35
+ prompt: (message: string) => Promise<string>;
36
+ progress: { update: (msg: string) => void; stop: (msg?: string) => void };
37
+ };