@openclaw/msteams 2026.3.13 → 2026.5.2-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 (175) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/index.ts +15 -12
  7. package/openclaw.plugin.json +553 -1
  8. package/package.json +46 -12
  9. package/runtime-api.ts +73 -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.test.ts +461 -0
  16. package/src/attachments/bot-framework.ts +362 -0
  17. package/src/attachments/download.ts +63 -19
  18. package/src/attachments/graph.test.ts +416 -0
  19. package/src/attachments/graph.ts +163 -72
  20. package/src/attachments/html.ts +33 -1
  21. package/src/attachments/payload.ts +1 -1
  22. package/src/attachments/remote-media.test.ts +137 -0
  23. package/src/attachments/remote-media.ts +75 -8
  24. package/src/attachments/shared.test.ts +138 -1
  25. package/src/attachments/shared.ts +193 -26
  26. package/src/attachments/types.ts +10 -0
  27. package/src/attachments.graph.test.ts +342 -0
  28. package/src/attachments.helpers.test.ts +246 -0
  29. package/src/attachments.test-helpers.ts +17 -0
  30. package/src/attachments.test.ts +163 -418
  31. package/src/attachments.ts +5 -5
  32. package/src/block-streaming-config.test.ts +61 -0
  33. package/src/channel-api.ts +1 -0
  34. package/src/channel.actions.test.ts +742 -0
  35. package/src/channel.directory.test.ts +145 -4
  36. package/src/channel.runtime.ts +56 -0
  37. package/src/channel.setup.ts +77 -0
  38. package/src/channel.test.ts +128 -0
  39. package/src/channel.ts +1077 -395
  40. package/src/config-schema.ts +6 -0
  41. package/src/config-ui-hints.ts +12 -0
  42. package/src/conversation-store-fs.test.ts +4 -5
  43. package/src/conversation-store-fs.ts +35 -51
  44. package/src/conversation-store-helpers.test.ts +202 -0
  45. package/src/conversation-store-helpers.ts +105 -0
  46. package/src/conversation-store-memory.ts +27 -23
  47. package/src/conversation-store.shared.test.ts +225 -0
  48. package/src/conversation-store.ts +30 -0
  49. package/src/directory-live.test.ts +156 -0
  50. package/src/directory-live.ts +7 -4
  51. package/src/doctor.ts +27 -0
  52. package/src/errors.test.ts +64 -1
  53. package/src/errors.ts +50 -9
  54. package/src/feedback-reflection-prompt.ts +117 -0
  55. package/src/feedback-reflection-store.ts +114 -0
  56. package/src/feedback-reflection.test.ts +237 -0
  57. package/src/feedback-reflection.ts +283 -0
  58. package/src/file-consent-helpers.test.ts +83 -0
  59. package/src/file-consent-helpers.ts +64 -11
  60. package/src/file-consent-invoke.ts +150 -0
  61. package/src/file-consent.test.ts +363 -0
  62. package/src/file-consent.ts +165 -4
  63. package/src/graph-chat.ts +5 -3
  64. package/src/graph-group-management.test.ts +318 -0
  65. package/src/graph-group-management.ts +168 -0
  66. package/src/graph-members.test.ts +89 -0
  67. package/src/graph-members.ts +48 -0
  68. package/src/graph-messages.actions.test.ts +243 -0
  69. package/src/graph-messages.read.test.ts +391 -0
  70. package/src/graph-messages.search.test.ts +213 -0
  71. package/src/graph-messages.test-helpers.ts +50 -0
  72. package/src/graph-messages.ts +534 -0
  73. package/src/graph-teams.test.ts +215 -0
  74. package/src/graph-teams.ts +114 -0
  75. package/src/graph-thread.test.ts +246 -0
  76. package/src/graph-thread.ts +146 -0
  77. package/src/graph-upload.test.ts +161 -4
  78. package/src/graph-upload.ts +147 -56
  79. package/src/graph.test.ts +516 -0
  80. package/src/graph.ts +233 -21
  81. package/src/inbound.test.ts +156 -1
  82. package/src/inbound.ts +101 -1
  83. package/src/media-helpers.ts +1 -1
  84. package/src/mentions.test.ts +27 -18
  85. package/src/mentions.ts +2 -2
  86. package/src/messenger.test.ts +504 -23
  87. package/src/messenger.ts +133 -52
  88. package/src/monitor-handler/access.ts +125 -0
  89. package/src/monitor-handler/inbound-media.test.ts +289 -0
  90. package/src/monitor-handler/inbound-media.ts +57 -5
  91. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  92. package/src/monitor-handler/message-handler.authz.test.ts +588 -74
  93. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  94. package/src/monitor-handler/message-handler.test-support.ts +100 -0
  95. package/src/monitor-handler/message-handler.thread-parent.test.ts +223 -0
  96. package/src/monitor-handler/message-handler.thread-session.test.ts +77 -0
  97. package/src/monitor-handler/message-handler.ts +470 -164
  98. package/src/monitor-handler/reaction-handler.test.ts +267 -0
  99. package/src/monitor-handler/reaction-handler.ts +210 -0
  100. package/src/monitor-handler/thread-session.ts +17 -0
  101. package/src/monitor-handler.adaptive-card.test.ts +162 -0
  102. package/src/monitor-handler.feedback-authz.test.ts +314 -0
  103. package/src/monitor-handler.file-consent.test.ts +281 -79
  104. package/src/monitor-handler.sso.test.ts +563 -0
  105. package/src/monitor-handler.test-helpers.ts +180 -0
  106. package/src/monitor-handler.ts +459 -115
  107. package/src/monitor-handler.types.ts +27 -0
  108. package/src/monitor-types.ts +1 -0
  109. package/src/monitor.lifecycle.test.ts +74 -10
  110. package/src/monitor.test.ts +35 -1
  111. package/src/monitor.ts +143 -46
  112. package/src/oauth.flow.ts +77 -0
  113. package/src/oauth.shared.ts +37 -0
  114. package/src/oauth.test.ts +305 -0
  115. package/src/oauth.token.ts +158 -0
  116. package/src/oauth.ts +130 -0
  117. package/src/outbound.test.ts +10 -11
  118. package/src/outbound.ts +62 -44
  119. package/src/pending-uploads-fs.test.ts +246 -0
  120. package/src/pending-uploads-fs.ts +235 -0
  121. package/src/pending-uploads.test.ts +173 -0
  122. package/src/pending-uploads.ts +34 -2
  123. package/src/policy.test.ts +11 -5
  124. package/src/policy.ts +5 -5
  125. package/src/polls.test.ts +106 -5
  126. package/src/polls.ts +15 -7
  127. package/src/presentation.ts +68 -0
  128. package/src/probe.test.ts +27 -8
  129. package/src/probe.ts +43 -9
  130. package/src/reply-dispatcher.test.ts +437 -0
  131. package/src/reply-dispatcher.ts +259 -73
  132. package/src/reply-stream-controller.test.ts +235 -0
  133. package/src/reply-stream-controller.ts +147 -0
  134. package/src/resolve-allowlist.test.ts +105 -1
  135. package/src/resolve-allowlist.ts +112 -7
  136. package/src/runtime.ts +6 -3
  137. package/src/sdk-types.ts +43 -3
  138. package/src/sdk.test.ts +666 -0
  139. package/src/sdk.ts +867 -16
  140. package/src/secret-contract.ts +49 -0
  141. package/src/secret-input.ts +1 -1
  142. package/src/send-context.ts +76 -9
  143. package/src/send.test.ts +389 -5
  144. package/src/send.ts +140 -32
  145. package/src/sent-message-cache.ts +30 -18
  146. package/src/session-route.ts +40 -0
  147. package/src/setup-core.ts +160 -0
  148. package/src/setup-surface.test.ts +202 -0
  149. package/src/setup-surface.ts +320 -0
  150. package/src/sso-token-store.test.ts +72 -0
  151. package/src/sso-token-store.ts +166 -0
  152. package/src/sso.ts +300 -0
  153. package/src/storage.ts +1 -1
  154. package/src/store-fs.ts +2 -2
  155. package/src/streaming-message.test.ts +262 -0
  156. package/src/streaming-message.ts +297 -0
  157. package/src/test-runtime.ts +1 -1
  158. package/src/thread-parent-context.test.ts +224 -0
  159. package/src/thread-parent-context.ts +159 -0
  160. package/src/token.test.ts +237 -50
  161. package/src/token.ts +162 -7
  162. package/src/user-agent.test.ts +86 -0
  163. package/src/user-agent.ts +53 -0
  164. package/src/webhook-timeouts.ts +27 -0
  165. package/src/welcome-card.test.ts +81 -0
  166. package/src/welcome-card.ts +57 -0
  167. package/test-api.ts +1 -0
  168. package/tsconfig.json +16 -0
  169. package/CHANGELOG.md +0 -107
  170. package/src/file-lock.ts +0 -1
  171. package/src/graph-users.test.ts +0 -66
  172. package/src/onboarding.ts +0 -381
  173. package/src/polls-store.test.ts +0 -38
  174. package/src/revoked-context.test.ts +0 -39
  175. package/src/token-response.test.ts +0 -23
@@ -0,0 +1,362 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { getMSTeamsRuntime } from "../runtime.js";
3
+ import { ensureUserAgentHeader } from "../user-agent.js";
4
+ import {
5
+ inferPlaceholder,
6
+ isUrlAllowed,
7
+ type MSTeamsAttachmentDownloadLogger,
8
+ type MSTeamsAttachmentFetchPolicy,
9
+ type MSTeamsAttachmentResolveFn,
10
+ resolveAttachmentFetchPolicy,
11
+ safeFetchWithPolicy,
12
+ } from "./shared.js";
13
+ import type {
14
+ MSTeamsAccessTokenProvider,
15
+ MSTeamsGraphMediaResult,
16
+ MSTeamsInboundMedia,
17
+ } from "./types.js";
18
+
19
+ /**
20
+ * Bot Framework Service token scope for requesting a token used against
21
+ * the Bot Connector (v3) REST endpoints such as `/v3/attachments/{id}`.
22
+ */
23
+ const BOT_FRAMEWORK_SCOPE = "https://api.botframework.com";
24
+
25
+ /**
26
+ * Detect Bot Framework personal chat ("a:") and MSA orgid ("8:orgid:") conversation
27
+ * IDs. These identifiers are not recognized by Graph's `/chats/{id}` endpoint, so we
28
+ * must fetch media via the Bot Framework v3 attachments endpoint instead.
29
+ *
30
+ * Graph-compatible IDs start with `19:` and are left untouched by this detector.
31
+ */
32
+ export function isBotFrameworkPersonalChatId(conversationId: string | null | undefined): boolean {
33
+ if (typeof conversationId !== "string") {
34
+ return false;
35
+ }
36
+ const trimmed = conversationId.trim();
37
+ return trimmed.startsWith("a:") || trimmed.startsWith("8:orgid:");
38
+ }
39
+
40
+ type BotFrameworkView = {
41
+ viewId?: string | null;
42
+ size?: number | null;
43
+ };
44
+
45
+ type BotFrameworkAttachmentInfo = {
46
+ name?: string | null;
47
+ type?: string | null;
48
+ views?: BotFrameworkView[] | null;
49
+ };
50
+
51
+ function normalizeServiceUrl(serviceUrl: string): string {
52
+ // Bot Framework service URLs sometimes carry a trailing slash; normalize so
53
+ // we can safely append `/v3/attachments/...` below.
54
+ return serviceUrl.replace(/\/+$/, "");
55
+ }
56
+
57
+ async function fetchBotFrameworkAttachmentInfo(params: {
58
+ serviceUrl: string;
59
+ attachmentId: string;
60
+ accessToken: string;
61
+ policy: MSTeamsAttachmentFetchPolicy;
62
+ fetchFn?: typeof fetch;
63
+ resolveFn?: MSTeamsAttachmentResolveFn;
64
+ logger?: MSTeamsAttachmentDownloadLogger;
65
+ }): Promise<BotFrameworkAttachmentInfo | undefined> {
66
+ const url = `${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}`;
67
+ // Use `safeFetchWithPolicy` instead of `fetchWithSsrFGuard`. The strict
68
+ // pinned undici dispatcher used by `fetchWithSsrFGuard` is incompatible
69
+ // with Node 24+'s built-in undici v7 and silently breaks Bot Framework
70
+ // attachment downloads (same root cause as the SharePoint fix in #63396).
71
+ // `safeFetchWithPolicy` already enforces hostname allowlist validation
72
+ // across every redirect hop, which is sufficient for these attachment
73
+ // service URLs.
74
+ let response: Response;
75
+ try {
76
+ response = await safeFetchWithPolicy({
77
+ url,
78
+ policy: params.policy,
79
+ fetchFn: params.fetchFn,
80
+ resolveFn: params.resolveFn,
81
+ requestInit: {
82
+ headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }),
83
+ },
84
+ });
85
+ } catch (err) {
86
+ params.logger?.warn?.("msteams botFramework attachmentInfo fetch failed", {
87
+ error: err instanceof Error ? err.message : String(err),
88
+ });
89
+ return undefined;
90
+ }
91
+ if (!response.ok) {
92
+ params.logger?.warn?.("msteams botFramework attachmentInfo non-ok", {
93
+ status: response.status,
94
+ });
95
+ return undefined;
96
+ }
97
+ try {
98
+ return (await response.json()) as BotFrameworkAttachmentInfo;
99
+ } catch (err) {
100
+ params.logger?.warn?.("msteams botFramework attachmentInfo parse failed", {
101
+ error: err instanceof Error ? err.message : String(err),
102
+ });
103
+ return undefined;
104
+ }
105
+ }
106
+
107
+ async function fetchBotFrameworkAttachmentView(params: {
108
+ serviceUrl: string;
109
+ attachmentId: string;
110
+ viewId: string;
111
+ accessToken: string;
112
+ maxBytes: number;
113
+ policy: MSTeamsAttachmentFetchPolicy;
114
+ fetchFn?: typeof fetch;
115
+ resolveFn?: MSTeamsAttachmentResolveFn;
116
+ logger?: MSTeamsAttachmentDownloadLogger;
117
+ }): Promise<Buffer | undefined> {
118
+ const url = `${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}/views/${encodeURIComponent(params.viewId)}`;
119
+ // See `fetchBotFrameworkAttachmentInfo` for why this uses
120
+ // `safeFetchWithPolicy` instead of `fetchWithSsrFGuard` on Node 24+ (#63396).
121
+ let response: Response;
122
+ try {
123
+ response = await safeFetchWithPolicy({
124
+ url,
125
+ policy: params.policy,
126
+ fetchFn: params.fetchFn,
127
+ resolveFn: params.resolveFn,
128
+ requestInit: {
129
+ headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }),
130
+ },
131
+ });
132
+ } catch (err) {
133
+ params.logger?.warn?.("msteams botFramework attachmentView fetch failed", {
134
+ error: err instanceof Error ? err.message : String(err),
135
+ });
136
+ return undefined;
137
+ }
138
+ if (!response.ok) {
139
+ params.logger?.warn?.("msteams botFramework attachmentView non-ok", {
140
+ status: response.status,
141
+ });
142
+ return undefined;
143
+ }
144
+ const contentLength = response.headers.get("content-length");
145
+ if (contentLength && Number(contentLength) > params.maxBytes) {
146
+ return undefined;
147
+ }
148
+ try {
149
+ const arrayBuffer = await response.arrayBuffer();
150
+ const buffer = Buffer.from(arrayBuffer);
151
+ if (buffer.byteLength > params.maxBytes) {
152
+ return undefined;
153
+ }
154
+ return buffer;
155
+ } catch (err) {
156
+ params.logger?.warn?.("msteams botFramework attachmentView body read failed", {
157
+ error: err instanceof Error ? err.message : String(err),
158
+ });
159
+ return undefined;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Download media for a single attachment via the Bot Framework v3 attachments
165
+ * endpoint. Used for personal DM conversations where the Graph `/chats/{id}`
166
+ * path is not usable because the Bot Framework conversation ID (`a:...`) is
167
+ * not a valid Graph chat identifier.
168
+ */
169
+ export async function downloadMSTeamsBotFrameworkAttachment(params: {
170
+ serviceUrl: string;
171
+ attachmentId: string;
172
+ tokenProvider?: MSTeamsAccessTokenProvider;
173
+ maxBytes: number;
174
+ allowHosts?: string[];
175
+ authAllowHosts?: string[];
176
+ fetchFn?: typeof fetch;
177
+ resolveFn?: MSTeamsAttachmentResolveFn;
178
+ fileNameHint?: string | null;
179
+ contentTypeHint?: string | null;
180
+ preserveFilenames?: boolean;
181
+ logger?: MSTeamsAttachmentDownloadLogger;
182
+ }): Promise<MSTeamsInboundMedia | undefined> {
183
+ if (!params.serviceUrl || !params.attachmentId || !params.tokenProvider) {
184
+ return undefined;
185
+ }
186
+ const policy: MSTeamsAttachmentFetchPolicy = resolveAttachmentFetchPolicy({
187
+ allowHosts: params.allowHosts,
188
+ authAllowHosts: params.authAllowHosts,
189
+ });
190
+ const baseUrl = `${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}`;
191
+ if (!isUrlAllowed(baseUrl, policy.allowHosts)) {
192
+ return undefined;
193
+ }
194
+
195
+ let accessToken: string;
196
+ try {
197
+ accessToken = await params.tokenProvider.getAccessToken(BOT_FRAMEWORK_SCOPE);
198
+ } catch (err) {
199
+ params.logger?.warn?.("msteams botFramework token acquisition failed", {
200
+ error: err instanceof Error ? err.message : String(err),
201
+ });
202
+ return undefined;
203
+ }
204
+ if (!accessToken) {
205
+ return undefined;
206
+ }
207
+
208
+ const info = await fetchBotFrameworkAttachmentInfo({
209
+ serviceUrl: params.serviceUrl,
210
+ attachmentId: params.attachmentId,
211
+ accessToken,
212
+ policy,
213
+ fetchFn: params.fetchFn,
214
+ resolveFn: params.resolveFn,
215
+ logger: params.logger,
216
+ });
217
+ if (!info) {
218
+ return undefined;
219
+ }
220
+
221
+ const views = Array.isArray(info.views) ? info.views : [];
222
+ // Prefer the "original" view when present, otherwise fall back to the first
223
+ // view the Bot Framework service returned.
224
+ const original = views.find((view) => view?.viewId === "original");
225
+ const candidateView = original ?? views.find((view) => typeof view?.viewId === "string");
226
+ const viewId =
227
+ typeof candidateView?.viewId === "string" && candidateView.viewId
228
+ ? candidateView.viewId
229
+ : undefined;
230
+ if (!viewId) {
231
+ return undefined;
232
+ }
233
+ if (
234
+ typeof candidateView?.size === "number" &&
235
+ candidateView.size > 0 &&
236
+ candidateView.size > params.maxBytes
237
+ ) {
238
+ return undefined;
239
+ }
240
+
241
+ const buffer = await fetchBotFrameworkAttachmentView({
242
+ serviceUrl: params.serviceUrl,
243
+ attachmentId: params.attachmentId,
244
+ viewId,
245
+ accessToken,
246
+ maxBytes: params.maxBytes,
247
+ policy,
248
+ fetchFn: params.fetchFn,
249
+ resolveFn: params.resolveFn,
250
+ logger: params.logger,
251
+ });
252
+ if (!buffer) {
253
+ return undefined;
254
+ }
255
+
256
+ const fileNameHint =
257
+ (typeof params.fileNameHint === "string" && params.fileNameHint) ||
258
+ (typeof info.name === "string" && info.name) ||
259
+ undefined;
260
+ const contentTypeHint =
261
+ (typeof params.contentTypeHint === "string" && params.contentTypeHint) ||
262
+ (typeof info.type === "string" && info.type) ||
263
+ undefined;
264
+
265
+ const mime = await getMSTeamsRuntime().media.detectMime({
266
+ buffer,
267
+ headerMime: contentTypeHint,
268
+ filePath: fileNameHint,
269
+ });
270
+
271
+ try {
272
+ const originalFilename = params.preserveFilenames ? fileNameHint : undefined;
273
+ const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(
274
+ buffer,
275
+ mime ?? contentTypeHint,
276
+ "inbound",
277
+ params.maxBytes,
278
+ originalFilename,
279
+ );
280
+ return {
281
+ path: saved.path,
282
+ contentType: saved.contentType,
283
+ placeholder: inferPlaceholder({ contentType: saved.contentType, fileName: fileNameHint }),
284
+ };
285
+ } catch (err) {
286
+ params.logger?.warn?.("msteams botFramework save failed", {
287
+ error: err instanceof Error ? err.message : String(err),
288
+ });
289
+ return undefined;
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Download media for every attachment referenced by a Bot Framework personal
295
+ * chat activity. Returns all successfully fetched media along with diagnostics
296
+ * compatible with `downloadMSTeamsGraphMedia`'s result shape so callers can
297
+ * reuse the existing logging path.
298
+ */
299
+ export async function downloadMSTeamsBotFrameworkAttachments(params: {
300
+ serviceUrl: string;
301
+ attachmentIds: string[];
302
+ tokenProvider?: MSTeamsAccessTokenProvider;
303
+ maxBytes: number;
304
+ allowHosts?: string[];
305
+ authAllowHosts?: string[];
306
+ fetchFn?: typeof fetch;
307
+ resolveFn?: MSTeamsAttachmentResolveFn;
308
+ fileNameHint?: string | null;
309
+ contentTypeHint?: string | null;
310
+ preserveFilenames?: boolean;
311
+ logger?: MSTeamsAttachmentDownloadLogger;
312
+ }): Promise<MSTeamsGraphMediaResult> {
313
+ const seen = new Set<string>();
314
+ const unique: string[] = [];
315
+ for (const id of params.attachmentIds ?? []) {
316
+ if (typeof id !== "string") {
317
+ continue;
318
+ }
319
+ const trimmed = id.trim();
320
+ if (!trimmed || seen.has(trimmed)) {
321
+ continue;
322
+ }
323
+ seen.add(trimmed);
324
+ unique.push(trimmed);
325
+ }
326
+ if (unique.length === 0 || !params.serviceUrl || !params.tokenProvider) {
327
+ return { media: [], attachmentCount: unique.length };
328
+ }
329
+
330
+ const media: MSTeamsInboundMedia[] = [];
331
+ for (const attachmentId of unique) {
332
+ try {
333
+ const item = await downloadMSTeamsBotFrameworkAttachment({
334
+ serviceUrl: params.serviceUrl,
335
+ attachmentId,
336
+ tokenProvider: params.tokenProvider,
337
+ maxBytes: params.maxBytes,
338
+ allowHosts: params.allowHosts,
339
+ authAllowHosts: params.authAllowHosts,
340
+ fetchFn: params.fetchFn,
341
+ resolveFn: params.resolveFn,
342
+ fileNameHint: params.fileNameHint,
343
+ contentTypeHint: params.contentTypeHint,
344
+ preserveFilenames: params.preserveFilenames,
345
+ logger: params.logger,
346
+ });
347
+ if (item) {
348
+ media.push(item);
349
+ }
350
+ } catch (err) {
351
+ params.logger?.warn?.("msteams botFramework attachment download failed", {
352
+ error: err instanceof Error ? err.message : String(err),
353
+ attachmentId,
354
+ });
355
+ }
356
+ }
357
+
358
+ return {
359
+ media,
360
+ attachmentCount: unique.length,
361
+ };
362
+ }
@@ -1,3 +1,7 @@
1
+ import {
2
+ normalizeLowercaseStringOrEmpty,
3
+ normalizeOptionalString,
4
+ } from "openclaw/plugin-sdk/text-runtime";
1
5
  import { getMSTeamsRuntime } from "../runtime.js";
2
6
  import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
3
7
  import {
@@ -6,12 +10,15 @@ import {
6
10
  isDownloadableAttachment,
7
11
  isRecord,
8
12
  isUrlAllowed,
13
+ type MSTeamsAttachmentDownloadLogger,
9
14
  type MSTeamsAttachmentFetchPolicy,
15
+ type MSTeamsAttachmentResolveFn,
10
16
  normalizeContentType,
11
17
  resolveMediaSsrfPolicy,
12
18
  resolveAttachmentFetchPolicy,
13
19
  resolveRequestUrl,
14
20
  safeFetchWithPolicy,
21
+ tryBuildGraphSharesUrlForSharedLink,
15
22
  } from "./shared.js";
16
23
  import type {
17
24
  MSTeamsAccessTokenProvider,
@@ -28,21 +35,20 @@ type DownloadCandidate = {
28
35
 
29
36
  function resolveDownloadCandidate(att: MSTeamsAttachmentLike): DownloadCandidate | null {
30
37
  const contentType = normalizeContentType(att.contentType);
31
- const name = typeof att.name === "string" ? att.name.trim() : "";
38
+ const name = normalizeOptionalString(att.name) ?? "";
32
39
 
33
40
  if (contentType === "application/vnd.microsoft.teams.file.download.info") {
34
41
  if (!isRecord(att.content)) {
35
42
  return null;
36
43
  }
37
- const downloadUrl =
38
- typeof att.content.downloadUrl === "string" ? att.content.downloadUrl.trim() : "";
44
+ const downloadUrl = normalizeOptionalString(att.content.downloadUrl) ?? "";
39
45
  if (!downloadUrl) {
40
46
  return null;
41
47
  }
42
48
 
43
- const fileType = typeof att.content.fileType === "string" ? att.content.fileType.trim() : "";
44
- const uniqueId = typeof att.content.uniqueId === "string" ? att.content.uniqueId.trim() : "";
45
- const fileName = typeof att.content.fileName === "string" ? att.content.fileName.trim() : "";
49
+ const fileType = normalizeOptionalString(att.content.fileType) ?? "";
50
+ const uniqueId = normalizeOptionalString(att.content.uniqueId) ?? "";
51
+ const fileName = normalizeOptionalString(att.content.fileName) ?? "";
46
52
 
47
53
  const fileHint = name || fileName || (uniqueId && fileType ? `${uniqueId}.${fileType}` : "");
48
54
  return {
@@ -57,22 +63,33 @@ function resolveDownloadCandidate(att: MSTeamsAttachmentLike): DownloadCandidate
57
63
  };
58
64
  }
59
65
 
60
- const contentUrl = typeof att.contentUrl === "string" ? att.contentUrl.trim() : "";
66
+ const contentUrl = normalizeOptionalString(att.contentUrl) ?? "";
61
67
  if (!contentUrl) {
62
68
  return null;
63
69
  }
64
70
 
71
+ // OneDrive/SharePoint shared links (delivered in 1:1 DMs when the user
72
+ // picks "Attach > OneDrive") cannot be fetched directly — the URL returns
73
+ // an HTML landing page rather than the file bytes. Rewrite them to the
74
+ // Graph shares endpoint so the auth fallback attaches a Graph-scoped token
75
+ // and the response is the real file content.
76
+ const sharesUrl = tryBuildGraphSharesUrlForSharedLink(contentUrl);
77
+ const resolvedUrl = sharesUrl ?? contentUrl;
78
+ // Graph shares returns raw bytes without a declared content type we can
79
+ // trust for routing — let the downloader infer MIME from the buffer.
80
+ const resolvedContentTypeHint = sharesUrl ? undefined : contentType;
81
+
65
82
  return {
66
- url: contentUrl,
83
+ url: resolvedUrl,
67
84
  fileHint: name || undefined,
68
- contentTypeHint: contentType,
85
+ contentTypeHint: resolvedContentTypeHint,
69
86
  placeholder: inferPlaceholder({ contentType, fileName: name }),
70
87
  };
71
88
  }
72
89
 
73
90
  function scopeCandidatesForUrl(url: string): string[] {
74
91
  try {
75
- const host = new URL(url).hostname.toLowerCase();
92
+ const host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
76
93
  const looksLikeGraph =
77
94
  host.endsWith("graph.microsoft.com") ||
78
95
  host.endsWith("sharepoint.com") ||
@@ -95,6 +112,7 @@ async function fetchWithAuthFallback(params: {
95
112
  tokenProvider?: MSTeamsAccessTokenProvider;
96
113
  fetchFn?: typeof fetch;
97
114
  requestInit?: RequestInit;
115
+ resolveFn?: MSTeamsAttachmentResolveFn;
98
116
  policy: MSTeamsAttachmentFetchPolicy;
99
117
  }): Promise<Response> {
100
118
  const firstAttempt = await safeFetchWithPolicy({
@@ -102,6 +120,7 @@ async function fetchWithAuthFallback(params: {
102
120
  policy: params.policy,
103
121
  fetchFn: params.fetchFn,
104
122
  requestInit: params.requestInit,
123
+ resolveFn: params.resolveFn,
105
124
  });
106
125
  if (firstAttempt.ok) {
107
126
  return firstAttempt;
@@ -131,6 +150,7 @@ async function fetchWithAuthFallback(params: {
131
150
  ...params.requestInit,
132
151
  headers: authHeaders,
133
152
  },
153
+ resolveFn: params.resolveFn,
134
154
  });
135
155
  if (authAttempt.ok) {
136
156
  return authAttempt;
@@ -162,8 +182,15 @@ export async function downloadMSTeamsAttachments(params: {
162
182
  allowHosts?: string[];
163
183
  authAllowHosts?: string[];
164
184
  fetchFn?: typeof fetch;
185
+ resolveFn?: MSTeamsAttachmentResolveFn;
165
186
  /** When true, embeds original filename in stored path for later extraction. */
166
187
  preserveFilenames?: boolean;
188
+ /**
189
+ * Optional logger used to surface inline data decode failures and remote
190
+ * media download errors. Errors that are not logged here are invisible at
191
+ * INFO level and block diagnosis of issues like #63396.
192
+ */
193
+ logger?: MSTeamsAttachmentDownloadLogger;
167
194
  }): Promise<MSTeamsInboundMedia[]> {
168
195
  const list = Array.isArray(params.attachments) ? params.attachments : [];
169
196
  if (list.length === 0) {
@@ -182,7 +209,10 @@ export async function downloadMSTeamsAttachments(params: {
182
209
  .map(resolveDownloadCandidate)
183
210
  .filter(Boolean) as DownloadCandidate[];
184
211
 
185
- const inlineCandidates = extractInlineImageCandidates(list);
212
+ const inlineCandidates = extractInlineImageCandidates(list, {
213
+ maxInlineBytes: params.maxBytes,
214
+ maxInlineTotalBytes: params.maxBytes,
215
+ });
186
216
 
187
217
  const seenUrls = new Set<string>();
188
218
  for (const inline of inlineCandidates) {
@@ -227,8 +257,10 @@ export async function downloadMSTeamsAttachments(params: {
227
257
  contentType: saved.contentType,
228
258
  placeholder: inline.placeholder,
229
259
  });
230
- } catch {
231
- // Ignore decode failures and continue.
260
+ } catch (err) {
261
+ params.logger?.warn?.("msteams inline attachment decode failed", {
262
+ error: err instanceof Error ? err.message : String(err),
263
+ });
232
264
  }
233
265
  }
234
266
  for (const candidate of candidates) {
@@ -244,24 +276,36 @@ export async function downloadMSTeamsAttachments(params: {
244
276
  placeholder: candidate.placeholder,
245
277
  preserveFilenames: params.preserveFilenames,
246
278
  ssrfPolicy,
279
+ // `fetchImpl` below already validates each hop against the hostname
280
+ // allowlist via `safeFetchWithPolicy`, so skip `fetchRemoteMedia`'s
281
+ // strict SSRF dispatcher (incompatible with Node 24+ / undici v7;
282
+ // see issue #63396).
283
+ useDirectFetch: true,
247
284
  fetchImpl: (input, init) =>
248
285
  fetchWithAuthFallback({
249
286
  url: resolveRequestUrl(input),
250
287
  tokenProvider: params.tokenProvider,
251
288
  fetchFn: params.fetchFn,
252
289
  requestInit: init,
290
+ resolveFn: params.resolveFn,
253
291
  policy,
254
292
  }),
255
293
  });
256
294
  out.push(media);
257
- } catch {
258
- // Ignore download failures and continue with next candidate.
295
+ } catch (err) {
296
+ params.logger?.warn?.("msteams attachment download failed", {
297
+ error: err instanceof Error ? err.message : String(err),
298
+ host: safeHostForLog(candidate.url),
299
+ });
259
300
  }
260
301
  }
261
302
  return out;
262
303
  }
263
304
 
264
- /**
265
- * @deprecated Use `downloadMSTeamsAttachments` instead (supports all file types).
266
- */
267
- export const downloadMSTeamsImageAttachments = downloadMSTeamsAttachments;
305
+ function safeHostForLog(url: string): string {
306
+ try {
307
+ return new URL(url).host;
308
+ } catch {
309
+ return "invalid-url";
310
+ }
311
+ }