@openclaw/msteams 2026.5.2-beta.2 → 2026.5.3-beta.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 (197) hide show
  1. package/dist/api.js +3 -0
  2. package/dist/channel-D7hdreTh.js +984 -0
  3. package/dist/channel-config-api.js +2 -0
  4. package/dist/channel-plugin-api.js +2 -0
  5. package/dist/channel.runtime-BC1ruIfN.js +573 -0
  6. package/dist/config-schema-B8QezH6t.js +15 -0
  7. package/dist/contract-api.js +2 -0
  8. package/dist/graph-users-9uQJepqr.js +1354 -0
  9. package/dist/index.js +22 -0
  10. package/dist/oauth-BWJyilR1.js +114 -0
  11. package/dist/oauth.token-xxpoLWy5.js +115 -0
  12. package/dist/policy-DTnU2GR7.js +142 -0
  13. package/dist/probe-D_H8yFps.js +2194 -0
  14. package/dist/resolve-allowlist-D41JSziq.js +219 -0
  15. package/dist/runtime-api-DV1iVMn1.js +28 -0
  16. package/dist/runtime-api.js +2 -0
  17. package/dist/secret-contract-BuoEXmPS.js +35 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/setup-entry.js +15 -0
  20. package/dist/setup-plugin-api.js +64 -0
  21. package/dist/setup-surface-BLkFQYIQ.js +313 -0
  22. package/dist/src-CFp1QpFd.js +4064 -0
  23. package/dist/test-api.js +2 -0
  24. package/package.json +14 -6
  25. package/api.ts +0 -3
  26. package/channel-config-api.ts +0 -1
  27. package/channel-plugin-api.ts +0 -2
  28. package/config-api.ts +0 -4
  29. package/contract-api.ts +0 -4
  30. package/index.ts +0 -20
  31. package/runtime-api.ts +0 -73
  32. package/secret-contract-api.ts +0 -5
  33. package/setup-entry.ts +0 -13
  34. package/setup-plugin-api.ts +0 -3
  35. package/src/ai-entity.ts +0 -7
  36. package/src/approval-auth.ts +0 -44
  37. package/src/attachments/bot-framework.test.ts +0 -461
  38. package/src/attachments/bot-framework.ts +0 -362
  39. package/src/attachments/download.ts +0 -311
  40. package/src/attachments/graph.test.ts +0 -416
  41. package/src/attachments/graph.ts +0 -484
  42. package/src/attachments/html.ts +0 -122
  43. package/src/attachments/payload.ts +0 -14
  44. package/src/attachments/remote-media.test.ts +0 -137
  45. package/src/attachments/remote-media.ts +0 -112
  46. package/src/attachments/shared.test.ts +0 -530
  47. package/src/attachments/shared.ts +0 -626
  48. package/src/attachments/types.ts +0 -47
  49. package/src/attachments.graph.test.ts +0 -342
  50. package/src/attachments.helpers.test.ts +0 -246
  51. package/src/attachments.test-helpers.ts +0 -17
  52. package/src/attachments.test.ts +0 -687
  53. package/src/attachments.ts +0 -18
  54. package/src/block-streaming-config.test.ts +0 -61
  55. package/src/channel-api.ts +0 -1
  56. package/src/channel.actions.test.ts +0 -742
  57. package/src/channel.directory.test.ts +0 -200
  58. package/src/channel.runtime.ts +0 -56
  59. package/src/channel.setup.ts +0 -77
  60. package/src/channel.test.ts +0 -128
  61. package/src/channel.ts +0 -1136
  62. package/src/config-schema.ts +0 -6
  63. package/src/config-ui-hints.ts +0 -12
  64. package/src/conversation-store-fs.test.ts +0 -74
  65. package/src/conversation-store-fs.ts +0 -149
  66. package/src/conversation-store-helpers.test.ts +0 -202
  67. package/src/conversation-store-helpers.ts +0 -105
  68. package/src/conversation-store-memory.ts +0 -51
  69. package/src/conversation-store.shared.test.ts +0 -225
  70. package/src/conversation-store.ts +0 -71
  71. package/src/directory-live.test.ts +0 -156
  72. package/src/directory-live.ts +0 -111
  73. package/src/doctor.ts +0 -27
  74. package/src/errors.test.ts +0 -133
  75. package/src/errors.ts +0 -246
  76. package/src/feedback-reflection-prompt.ts +0 -117
  77. package/src/feedback-reflection-store.ts +0 -114
  78. package/src/feedback-reflection.test.ts +0 -237
  79. package/src/feedback-reflection.ts +0 -283
  80. package/src/file-consent-helpers.test.ts +0 -326
  81. package/src/file-consent-helpers.ts +0 -126
  82. package/src/file-consent-invoke.ts +0 -150
  83. package/src/file-consent.test.ts +0 -363
  84. package/src/file-consent.ts +0 -287
  85. package/src/graph-chat.ts +0 -55
  86. package/src/graph-group-management.test.ts +0 -318
  87. package/src/graph-group-management.ts +0 -168
  88. package/src/graph-members.test.ts +0 -89
  89. package/src/graph-members.ts +0 -48
  90. package/src/graph-messages.actions.test.ts +0 -243
  91. package/src/graph-messages.read.test.ts +0 -391
  92. package/src/graph-messages.search.test.ts +0 -213
  93. package/src/graph-messages.test-helpers.ts +0 -50
  94. package/src/graph-messages.ts +0 -534
  95. package/src/graph-teams.test.ts +0 -215
  96. package/src/graph-teams.ts +0 -114
  97. package/src/graph-thread.test.ts +0 -246
  98. package/src/graph-thread.ts +0 -146
  99. package/src/graph-upload.test.ts +0 -258
  100. package/src/graph-upload.ts +0 -531
  101. package/src/graph-users.ts +0 -29
  102. package/src/graph.test.ts +0 -516
  103. package/src/graph.ts +0 -293
  104. package/src/inbound.test.ts +0 -221
  105. package/src/inbound.ts +0 -148
  106. package/src/index.ts +0 -4
  107. package/src/media-helpers.test.ts +0 -202
  108. package/src/media-helpers.ts +0 -105
  109. package/src/mentions.test.ts +0 -244
  110. package/src/mentions.ts +0 -114
  111. package/src/messenger.test.ts +0 -865
  112. package/src/messenger.ts +0 -605
  113. package/src/monitor-handler/access.ts +0 -125
  114. package/src/monitor-handler/inbound-media.test.ts +0 -289
  115. package/src/monitor-handler/inbound-media.ts +0 -180
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  117. package/src/monitor-handler/message-handler.authz.test.ts +0 -669
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  119. package/src/monitor-handler/message-handler.test-support.ts +0 -100
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -223
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -77
  122. package/src/monitor-handler/message-handler.ts +0 -1000
  123. package/src/monitor-handler/reaction-handler.test.ts +0 -267
  124. package/src/monitor-handler/reaction-handler.ts +0 -210
  125. package/src/monitor-handler/thread-session.ts +0 -17
  126. package/src/monitor-handler.adaptive-card.test.ts +0 -162
  127. package/src/monitor-handler.feedback-authz.test.ts +0 -314
  128. package/src/monitor-handler.file-consent.test.ts +0 -423
  129. package/src/monitor-handler.sso.test.ts +0 -563
  130. package/src/monitor-handler.test-helpers.ts +0 -180
  131. package/src/monitor-handler.ts +0 -534
  132. package/src/monitor-handler.types.ts +0 -27
  133. package/src/monitor-types.ts +0 -6
  134. package/src/monitor.lifecycle.test.ts +0 -278
  135. package/src/monitor.test.ts +0 -119
  136. package/src/monitor.ts +0 -442
  137. package/src/oauth.flow.ts +0 -77
  138. package/src/oauth.shared.ts +0 -37
  139. package/src/oauth.test.ts +0 -305
  140. package/src/oauth.token.ts +0 -158
  141. package/src/oauth.ts +0 -130
  142. package/src/outbound.test.ts +0 -130
  143. package/src/outbound.ts +0 -71
  144. package/src/pending-uploads-fs.test.ts +0 -246
  145. package/src/pending-uploads-fs.ts +0 -235
  146. package/src/pending-uploads.test.ts +0 -173
  147. package/src/pending-uploads.ts +0 -121
  148. package/src/policy.test.ts +0 -240
  149. package/src/policy.ts +0 -262
  150. package/src/polls-store-memory.ts +0 -32
  151. package/src/polls.test.ts +0 -160
  152. package/src/polls.ts +0 -323
  153. package/src/presentation.ts +0 -68
  154. package/src/probe.test.ts +0 -77
  155. package/src/probe.ts +0 -132
  156. package/src/reply-dispatcher.test.ts +0 -437
  157. package/src/reply-dispatcher.ts +0 -346
  158. package/src/reply-stream-controller.test.ts +0 -235
  159. package/src/reply-stream-controller.ts +0 -147
  160. package/src/resolve-allowlist.test.ts +0 -250
  161. package/src/resolve-allowlist.ts +0 -309
  162. package/src/revoked-context.ts +0 -17
  163. package/src/runtime.ts +0 -9
  164. package/src/sdk-types.ts +0 -59
  165. package/src/sdk.test.ts +0 -666
  166. package/src/sdk.ts +0 -884
  167. package/src/secret-contract.ts +0 -49
  168. package/src/secret-input.ts +0 -7
  169. package/src/send-context.ts +0 -231
  170. package/src/send.test.ts +0 -493
  171. package/src/send.ts +0 -637
  172. package/src/sent-message-cache.test.ts +0 -15
  173. package/src/sent-message-cache.ts +0 -56
  174. package/src/session-route.ts +0 -40
  175. package/src/setup-core.ts +0 -160
  176. package/src/setup-surface.test.ts +0 -202
  177. package/src/setup-surface.ts +0 -320
  178. package/src/sso-token-store.test.ts +0 -72
  179. package/src/sso-token-store.ts +0 -166
  180. package/src/sso.ts +0 -300
  181. package/src/storage.ts +0 -25
  182. package/src/store-fs.ts +0 -44
  183. package/src/streaming-message.test.ts +0 -262
  184. package/src/streaming-message.ts +0 -297
  185. package/src/test-runtime.ts +0 -16
  186. package/src/thread-parent-context.test.ts +0 -224
  187. package/src/thread-parent-context.ts +0 -159
  188. package/src/token-response.ts +0 -11
  189. package/src/token.test.ts +0 -259
  190. package/src/token.ts +0 -195
  191. package/src/user-agent.test.ts +0 -86
  192. package/src/user-agent.ts +0 -53
  193. package/src/webhook-timeouts.ts +0 -27
  194. package/src/welcome-card.test.ts +0 -81
  195. package/src/welcome-card.ts +0 -57
  196. package/test-api.ts +0 -1
  197. package/tsconfig.json +0 -16
package/src/monitor.ts DELETED
@@ -1,442 +0,0 @@
1
- import type { Request, Response } from "express";
2
- import {
3
- DEFAULT_WEBHOOK_MAX_BODY_BYTES,
4
- keepHttpServerTaskAlive,
5
- mergeAllowlist,
6
- summarizeMapping,
7
- type OpenClawConfig,
8
- type RuntimeEnv,
9
- } from "../runtime-api.js";
10
- import { createMSTeamsConversationStoreFs } from "./conversation-store-fs.js";
11
- import type { MSTeamsConversationStore } from "./conversation-store.js";
12
- import { formatUnknownError } from "./errors.js";
13
- import type { MSTeamsAdapter } from "./messenger.js";
14
- import { registerMSTeamsHandlers, type MSTeamsActivityHandler } from "./monitor-handler.js";
15
- import { createMSTeamsPollStoreFs, type MSTeamsPollStore } from "./polls.js";
16
- import {
17
- resolveMSTeamsChannelAllowlist,
18
- resolveMSTeamsUserAllowlist,
19
- } from "./resolve-allowlist.js";
20
- import { getMSTeamsRuntime } from "./runtime.js";
21
- import {
22
- createBotFrameworkJwtValidator,
23
- createMSTeamsAdapter,
24
- createMSTeamsTokenProvider,
25
- loadMSTeamsSdkWithAuth,
26
- } from "./sdk.js";
27
- import { createMSTeamsSsoTokenStoreFs } from "./sso-token-store.js";
28
- import type { MSTeamsSsoDeps } from "./sso.js";
29
- import { resolveMSTeamsCredentials } from "./token.js";
30
- import { applyMSTeamsWebhookTimeouts } from "./webhook-timeouts.js";
31
-
32
- type MonitorMSTeamsOpts = {
33
- cfg: OpenClawConfig;
34
- runtime?: RuntimeEnv;
35
- abortSignal?: AbortSignal;
36
- conversationStore?: MSTeamsConversationStore;
37
- pollStore?: MSTeamsPollStore;
38
- };
39
-
40
- type MonitorMSTeamsResult = {
41
- app: unknown;
42
- shutdown: () => Promise<void>;
43
- };
44
-
45
- const MSTEAMS_WEBHOOK_MAX_BODY_BYTES = DEFAULT_WEBHOOK_MAX_BODY_BYTES;
46
- export async function monitorMSTeamsProvider(
47
- opts: MonitorMSTeamsOpts,
48
- ): Promise<MonitorMSTeamsResult> {
49
- const core = getMSTeamsRuntime();
50
- const log = core.logging.getChildLogger({ name: "msteams" });
51
- let cfg = opts.cfg;
52
- let msteamsCfg = cfg.channels?.msteams;
53
- if (!msteamsCfg?.enabled) {
54
- log.debug?.("msteams provider disabled");
55
- return { app: null, shutdown: async () => {} };
56
- }
57
-
58
- const creds = resolveMSTeamsCredentials(msteamsCfg);
59
- if (!creds) {
60
- log.error("msteams credentials not configured");
61
- return { app: null, shutdown: async () => {} };
62
- }
63
- const appId = creds.appId; // Extract for use in closures
64
-
65
- const runtime: RuntimeEnv = opts.runtime ?? {
66
- log: console.log,
67
- error: console.error,
68
- exit: (code: number): never => {
69
- throw new Error(`exit ${code}`);
70
- },
71
- };
72
-
73
- let allowFrom = msteamsCfg.allowFrom;
74
- let groupAllowFrom = msteamsCfg.groupAllowFrom;
75
- let teamsConfig = msteamsCfg.teams;
76
-
77
- const cleanAllowEntry = (entry: string) =>
78
- entry
79
- .replace(/^(msteams|teams):/i, "")
80
- .replace(/^user:/i, "")
81
- .trim();
82
-
83
- const resolveAllowlistUsers = async (label: string, entries: string[]) => {
84
- if (entries.length === 0) {
85
- return { additions: [], unresolved: [] };
86
- }
87
- const resolved = await resolveMSTeamsUserAllowlist({ cfg, entries });
88
- const additions: string[] = [];
89
- const unresolved: string[] = [];
90
- for (const entry of resolved) {
91
- if (entry.resolved && entry.id) {
92
- additions.push(entry.id);
93
- } else {
94
- unresolved.push(entry.input);
95
- }
96
- }
97
- const mapping = resolved
98
- .filter((entry) => entry.resolved && entry.id)
99
- .map((entry) => `${entry.input}→${entry.id}`);
100
- summarizeMapping(label, mapping, unresolved, runtime);
101
- return { additions, unresolved };
102
- };
103
-
104
- try {
105
- const allowEntries =
106
- allowFrom?.map((entry) => cleanAllowEntry(entry)).filter((entry) => entry && entry !== "*") ??
107
- [];
108
- if (allowEntries.length > 0) {
109
- const { additions } = await resolveAllowlistUsers("msteams users", allowEntries);
110
- allowFrom = mergeAllowlist({ existing: allowFrom, additions });
111
- }
112
-
113
- if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) {
114
- const groupEntries = groupAllowFrom
115
- .map((entry) => cleanAllowEntry(entry))
116
- .filter((entry) => entry && entry !== "*");
117
- if (groupEntries.length > 0) {
118
- const { additions } = await resolveAllowlistUsers("msteams group users", groupEntries);
119
- groupAllowFrom = mergeAllowlist({ existing: groupAllowFrom, additions });
120
- }
121
- }
122
-
123
- if (teamsConfig && Object.keys(teamsConfig).length > 0) {
124
- const entries: Array<{ input: string; teamKey: string; channelKey?: string }> = [];
125
- for (const [teamKey, teamCfg] of Object.entries(teamsConfig)) {
126
- if (teamKey === "*") {
127
- continue;
128
- }
129
- const channels = teamCfg?.channels ?? {};
130
- const channelKeys = Object.keys(channels).filter((key) => key !== "*");
131
- if (channelKeys.length === 0) {
132
- entries.push({ input: teamKey, teamKey });
133
- continue;
134
- }
135
- for (const channelKey of channelKeys) {
136
- entries.push({
137
- input: `${teamKey}/${channelKey}`,
138
- teamKey,
139
- channelKey,
140
- });
141
- }
142
- }
143
-
144
- if (entries.length > 0) {
145
- const resolved = await resolveMSTeamsChannelAllowlist({
146
- cfg,
147
- entries: entries.map((entry) => entry.input),
148
- });
149
- const mapping: string[] = [];
150
- const unresolved: string[] = [];
151
- const nextTeams = { ...teamsConfig };
152
-
153
- resolved.forEach((entry, idx) => {
154
- const source = entries[idx];
155
- if (!source) {
156
- return;
157
- }
158
- const sourceTeam = teamsConfig?.[source.teamKey] ?? {};
159
- if (!entry.resolved || !entry.teamId) {
160
- unresolved.push(entry.input);
161
- return;
162
- }
163
- mapping.push(
164
- entry.channelId
165
- ? `${entry.input}→${entry.teamId}/${entry.channelId}`
166
- : `${entry.input}→${entry.teamId}`,
167
- );
168
- const existing = nextTeams[entry.teamId] ?? {};
169
- const mergedChannels = {
170
- ...sourceTeam.channels,
171
- ...existing.channels,
172
- };
173
- const mergedTeam = { ...sourceTeam, ...existing, channels: mergedChannels };
174
- nextTeams[entry.teamId] = mergedTeam;
175
- if (source.channelKey && entry.channelId) {
176
- const sourceChannel = sourceTeam.channels?.[source.channelKey];
177
- if (sourceChannel) {
178
- nextTeams[entry.teamId] = {
179
- ...mergedTeam,
180
- channels: {
181
- ...mergedChannels,
182
- [entry.channelId]: {
183
- ...sourceChannel,
184
- ...mergedChannels?.[entry.channelId],
185
- },
186
- },
187
- };
188
- }
189
- }
190
- });
191
-
192
- teamsConfig = nextTeams;
193
- summarizeMapping("msteams channels", mapping, unresolved, runtime);
194
- }
195
- }
196
- } catch (err) {
197
- runtime.log?.(`msteams resolve failed; using config entries. ${formatUnknownError(err)}`);
198
- }
199
-
200
- msteamsCfg = {
201
- ...msteamsCfg,
202
- allowFrom,
203
- groupAllowFrom,
204
- teams: teamsConfig,
205
- };
206
- cfg = {
207
- ...cfg,
208
- channels: {
209
- ...cfg.channels,
210
- msteams: msteamsCfg,
211
- },
212
- };
213
-
214
- const port = msteamsCfg.webhook?.port ?? 3978;
215
- const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "msteams");
216
- const MB = 1024 * 1024;
217
- const agentDefaults = cfg.agents?.defaults;
218
- const mediaMaxBytes =
219
- typeof agentDefaults?.mediaMaxMb === "number" && agentDefaults.mediaMaxMb > 0
220
- ? Math.floor(agentDefaults.mediaMaxMb * MB)
221
- : 8 * MB;
222
- const conversationStore = opts.conversationStore ?? createMSTeamsConversationStoreFs();
223
- const pollStore = opts.pollStore ?? createMSTeamsPollStoreFs();
224
-
225
- log.info(`starting provider (port ${port})`);
226
-
227
- // Dynamic import to avoid loading SDK when provider is disabled
228
- const express = await import("express");
229
-
230
- const { sdk, app } = await loadMSTeamsSdkWithAuth(creds);
231
-
232
- // Build a token provider adapter for Graph API operations
233
- const tokenProvider = createMSTeamsTokenProvider(app);
234
-
235
- const adapter = createMSTeamsAdapter(app, sdk);
236
-
237
- // Build SSO deps when the operator has opted in and a connection name
238
- // is configured. Leaving `sso` undefined matches the pre-SSO behavior
239
- // (the plugin will still ack signin invokes, but will not attempt a
240
- // Bot Framework token exchange or persist anything).
241
- let ssoDeps: MSTeamsSsoDeps | undefined;
242
- if (msteamsCfg.sso?.enabled && msteamsCfg.sso.connectionName) {
243
- ssoDeps = {
244
- tokenProvider,
245
- tokenStore: createMSTeamsSsoTokenStoreFs(),
246
- connectionName: msteamsCfg.sso.connectionName,
247
- };
248
- log.debug?.("msteams sso enabled", {
249
- connectionName: msteamsCfg.sso.connectionName,
250
- });
251
- }
252
-
253
- // Build a simple ActivityHandler-compatible object
254
- const handler = buildActivityHandler();
255
- registerMSTeamsHandlers(handler, {
256
- cfg,
257
- runtime,
258
- appId,
259
- adapter: adapter as unknown as MSTeamsAdapter,
260
- tokenProvider,
261
- textLimit,
262
- mediaMaxBytes,
263
- conversationStore,
264
- pollStore,
265
- log,
266
- sso: ssoDeps,
267
- });
268
-
269
- // Create Express server
270
- const expressApp = express.default();
271
-
272
- // Cheap pre-parse auth gate: reject requests without a Bearer token before
273
- // spending CPU/memory on JSON body parsing. This prevents unauthenticated
274
- // request floods from forcing body parsing on internet-exposed webhooks.
275
- expressApp.use((req: Request, res: Response, next: (err?: unknown) => void) => {
276
- const auth = req.headers.authorization;
277
- if (!auth || !auth.startsWith("Bearer ")) {
278
- res.status(401).json({ error: "Unauthorized" });
279
- return;
280
- }
281
- next();
282
- });
283
-
284
- // JWT validation — verify Bot Framework tokens using the Teams SDK's
285
- // JwtValidator (validates signature via JWKS, audience, issuer, expiration).
286
- const jwtValidator = await createBotFrameworkJwtValidator(creds);
287
- expressApp.use((req: Request, res: Response, next: (err?: unknown) => void) => {
288
- // Authorization header is guaranteed by the pre-parse auth gate above.
289
- // `serviceUrl` is optional, so authenticate from headers alone before body
290
- // I/O to avoid spending memory and CPU on unauthenticated requests.
291
- const authHeader = req.headers.authorization!;
292
- jwtValidator
293
- .validate(authHeader)
294
- .then((valid) => {
295
- if (!valid) {
296
- log.debug?.("JWT validation failed");
297
- res.status(401).json({ error: "Unauthorized" });
298
- return;
299
- }
300
- next();
301
- })
302
- .catch((err) => {
303
- log.debug?.(`JWT validation error: ${formatUnknownError(err)}`);
304
- res.status(401).json({ error: "Unauthorized" });
305
- });
306
- });
307
-
308
- expressApp.use(express.json({ limit: MSTEAMS_WEBHOOK_MAX_BODY_BYTES }));
309
- expressApp.use((err: unknown, _req: Request, res: Response, next: (err?: unknown) => void) => {
310
- if (err && typeof err === "object" && "status" in err && err.status === 413) {
311
- res.status(413).json({ error: "Payload too large" });
312
- return;
313
- }
314
- next(err);
315
- });
316
-
317
- // Set up the messages endpoint - use configured path and /api/messages as fallback
318
- const configuredPath = msteamsCfg.webhook?.path ?? "/api/messages";
319
- const messageHandler = (req: Request, res: Response) => {
320
- void adapter
321
- .process(req, res, (context: unknown) => handler.run!(context))
322
- .catch((err: unknown) => {
323
- log.error("msteams webhook failed", { error: formatUnknownError(err) });
324
- });
325
- };
326
-
327
- // Listen on configured path and /api/messages (standard Bot Framework path)
328
- expressApp.post(configuredPath, messageHandler);
329
- if (configuredPath !== "/api/messages") {
330
- expressApp.post("/api/messages", messageHandler);
331
- }
332
-
333
- log.debug?.("listening on paths", {
334
- primary: configuredPath,
335
- fallback: "/api/messages",
336
- });
337
-
338
- // Start listening and fail fast if bind/listen fails.
339
- const httpServer = expressApp.listen(port);
340
- await new Promise<void>((resolve, reject) => {
341
- const onListening = () => {
342
- httpServer.off("error", onError);
343
- log.info(`msteams provider started on port ${port}`);
344
- resolve();
345
- };
346
- const onError = (err: unknown) => {
347
- httpServer.off("listening", onListening);
348
- log.error("msteams server error", { error: formatUnknownError(err) });
349
- reject(err);
350
- };
351
- httpServer.once("listening", onListening);
352
- httpServer.once("error", onError);
353
- });
354
- applyMSTeamsWebhookTimeouts(httpServer);
355
-
356
- httpServer.on("error", (err) => {
357
- log.error("msteams server error", { error: formatUnknownError(err) });
358
- });
359
-
360
- const shutdown = async () => {
361
- log.info("shutting down msteams provider");
362
- return new Promise<void>((resolve) => {
363
- httpServer.close((err) => {
364
- if (err) {
365
- log.debug?.("msteams server close error", { error: formatUnknownError(err) });
366
- }
367
- resolve();
368
- });
369
- });
370
- };
371
-
372
- // Keep this task alive until close so gateway runtime does not treat startup as exit.
373
- await keepHttpServerTaskAlive({
374
- server: httpServer,
375
- abortSignal: opts.abortSignal,
376
- onAbort: shutdown,
377
- });
378
-
379
- return { app: expressApp, shutdown };
380
- }
381
-
382
- /**
383
- * Build a minimal ActivityHandler-compatible object that supports
384
- * onMessage / onMembersAdded registration and a run() method.
385
- */
386
- function buildActivityHandler(): MSTeamsActivityHandler {
387
- type Handler = (context: unknown, next: () => Promise<void>) => Promise<void>;
388
- const messageHandlers: Handler[] = [];
389
- const membersAddedHandlers: Handler[] = [];
390
- const reactionsAddedHandlers: Handler[] = [];
391
- const reactionsRemovedHandlers: Handler[] = [];
392
-
393
- const handler: MSTeamsActivityHandler = {
394
- onMessage(cb) {
395
- messageHandlers.push(cb);
396
- return handler;
397
- },
398
- onMembersAdded(cb) {
399
- membersAddedHandlers.push(cb);
400
- return handler;
401
- },
402
- onReactionsAdded(cb) {
403
- reactionsAddedHandlers.push(cb);
404
- return handler;
405
- },
406
- onReactionsRemoved(cb) {
407
- reactionsRemovedHandlers.push(cb);
408
- return handler;
409
- },
410
- async run(context: unknown) {
411
- const ctx = context as { activity?: { type?: string } };
412
- const activityType = ctx?.activity?.type;
413
- const noop = async () => {};
414
-
415
- if (activityType === "message") {
416
- for (const h of messageHandlers) {
417
- await h(context, noop);
418
- }
419
- } else if (activityType === "conversationUpdate") {
420
- for (const h of membersAddedHandlers) {
421
- await h(context, noop);
422
- }
423
- } else if (activityType === "messageReaction") {
424
- const activity = (
425
- ctx as { activity?: { reactionsAdded?: unknown[]; reactionsRemoved?: unknown[] } }
426
- )?.activity;
427
- if (activity?.reactionsAdded?.length) {
428
- for (const h of reactionsAddedHandlers) {
429
- await h(context, noop);
430
- }
431
- }
432
- if (activity?.reactionsRemoved?.length) {
433
- for (const h of reactionsRemovedHandlers) {
434
- await h(context, noop);
435
- }
436
- }
437
- }
438
- },
439
- };
440
-
441
- return handler;
442
- }
package/src/oauth.flow.ts DELETED
@@ -1,77 +0,0 @@
1
- import { generateHexPkceVerifierChallenge } from "openclaw/plugin-sdk/provider-auth";
2
- import {
3
- generateOAuthState,
4
- parseOAuthCallbackInput,
5
- waitForLocalOAuthCallback,
6
- } from "openclaw/plugin-sdk/provider-auth-runtime";
7
- import { isWSL2Sync } from "openclaw/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
- };