@kodelyth/msteams 2026.5.42 → 2026.6.1

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 (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
package/src/monitor.ts DELETED
@@ -1,476 +0,0 @@
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 KlawConfig,
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: KlawConfig;
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
- }
package/src/oauth.flow.ts DELETED
@@ -1,77 +0,0 @@
1
- import { generateHexPkceVerifierChallenge } from "klaw/plugin-sdk/provider-auth";
2
- import {
3
- generateOAuthState,
4
- parseOAuthCallbackInput,
5
- waitForLocalOAuthCallback,
6
- } from "klaw/plugin-sdk/provider-auth-runtime";
7
- import { isWSL2Sync } from "klaw/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
- }
@@ -1,37 +0,0 @@
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
- };