@openclaw/msteams 2026.5.2 → 2026.5.3-beta.2

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
@@ -1,362 +0,0 @@
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,311 +0,0 @@
1
- import {
2
- normalizeLowercaseStringOrEmpty,
3
- normalizeOptionalString,
4
- } from "openclaw/plugin-sdk/text-runtime";
5
- import { getMSTeamsRuntime } from "../runtime.js";
6
- import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
7
- import {
8
- extractInlineImageCandidates,
9
- inferPlaceholder,
10
- isDownloadableAttachment,
11
- isRecord,
12
- isUrlAllowed,
13
- type MSTeamsAttachmentDownloadLogger,
14
- type MSTeamsAttachmentFetchPolicy,
15
- type MSTeamsAttachmentResolveFn,
16
- normalizeContentType,
17
- resolveMediaSsrfPolicy,
18
- resolveAttachmentFetchPolicy,
19
- resolveRequestUrl,
20
- safeFetchWithPolicy,
21
- tryBuildGraphSharesUrlForSharedLink,
22
- } from "./shared.js";
23
- import type {
24
- MSTeamsAccessTokenProvider,
25
- MSTeamsAttachmentLike,
26
- MSTeamsInboundMedia,
27
- } from "./types.js";
28
-
29
- type DownloadCandidate = {
30
- url: string;
31
- fileHint?: string;
32
- contentTypeHint?: string;
33
- placeholder: string;
34
- };
35
-
36
- function resolveDownloadCandidate(att: MSTeamsAttachmentLike): DownloadCandidate | null {
37
- const contentType = normalizeContentType(att.contentType);
38
- const name = normalizeOptionalString(att.name) ?? "";
39
-
40
- if (contentType === "application/vnd.microsoft.teams.file.download.info") {
41
- if (!isRecord(att.content)) {
42
- return null;
43
- }
44
- const downloadUrl = normalizeOptionalString(att.content.downloadUrl) ?? "";
45
- if (!downloadUrl) {
46
- return null;
47
- }
48
-
49
- const fileType = normalizeOptionalString(att.content.fileType) ?? "";
50
- const uniqueId = normalizeOptionalString(att.content.uniqueId) ?? "";
51
- const fileName = normalizeOptionalString(att.content.fileName) ?? "";
52
-
53
- const fileHint = name || fileName || (uniqueId && fileType ? `${uniqueId}.${fileType}` : "");
54
- return {
55
- url: downloadUrl,
56
- fileHint: fileHint || undefined,
57
- contentTypeHint: undefined,
58
- placeholder: inferPlaceholder({
59
- contentType,
60
- fileName: fileHint,
61
- fileType,
62
- }),
63
- };
64
- }
65
-
66
- const contentUrl = normalizeOptionalString(att.contentUrl) ?? "";
67
- if (!contentUrl) {
68
- return null;
69
- }
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
-
82
- return {
83
- url: resolvedUrl,
84
- fileHint: name || undefined,
85
- contentTypeHint: resolvedContentTypeHint,
86
- placeholder: inferPlaceholder({ contentType, fileName: name }),
87
- };
88
- }
89
-
90
- function scopeCandidatesForUrl(url: string): string[] {
91
- try {
92
- const host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
93
- const looksLikeGraph =
94
- host.endsWith("graph.microsoft.com") ||
95
- host.endsWith("sharepoint.com") ||
96
- host.endsWith("1drv.ms") ||
97
- host.includes("sharepoint");
98
- return looksLikeGraph
99
- ? ["https://graph.microsoft.com", "https://api.botframework.com"]
100
- : ["https://api.botframework.com", "https://graph.microsoft.com"];
101
- } catch {
102
- return ["https://api.botframework.com", "https://graph.microsoft.com"];
103
- }
104
- }
105
-
106
- function isRedirectStatus(status: number): boolean {
107
- return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
108
- }
109
-
110
- async function fetchWithAuthFallback(params: {
111
- url: string;
112
- tokenProvider?: MSTeamsAccessTokenProvider;
113
- fetchFn?: typeof fetch;
114
- requestInit?: RequestInit;
115
- resolveFn?: MSTeamsAttachmentResolveFn;
116
- policy: MSTeamsAttachmentFetchPolicy;
117
- }): Promise<Response> {
118
- const firstAttempt = await safeFetchWithPolicy({
119
- url: params.url,
120
- policy: params.policy,
121
- fetchFn: params.fetchFn,
122
- requestInit: params.requestInit,
123
- resolveFn: params.resolveFn,
124
- });
125
- if (firstAttempt.ok) {
126
- return firstAttempt;
127
- }
128
- if (!params.tokenProvider) {
129
- return firstAttempt;
130
- }
131
- if (firstAttempt.status !== 401 && firstAttempt.status !== 403) {
132
- return firstAttempt;
133
- }
134
- if (!isUrlAllowed(params.url, params.policy.authAllowHosts)) {
135
- return firstAttempt;
136
- }
137
-
138
- const scopes = scopeCandidatesForUrl(params.url);
139
- const fetchFn = params.fetchFn ?? fetch;
140
- for (const scope of scopes) {
141
- try {
142
- const token = await params.tokenProvider.getAccessToken(scope);
143
- const authHeaders = new Headers(params.requestInit?.headers);
144
- authHeaders.set("Authorization", `Bearer ${token}`);
145
- const authAttempt = await safeFetchWithPolicy({
146
- url: params.url,
147
- policy: params.policy,
148
- fetchFn,
149
- requestInit: {
150
- ...params.requestInit,
151
- headers: authHeaders,
152
- },
153
- resolveFn: params.resolveFn,
154
- });
155
- if (authAttempt.ok) {
156
- return authAttempt;
157
- }
158
- if (isRedirectStatus(authAttempt.status)) {
159
- // Redirects in guarded fetch mode must propagate to the outer guard.
160
- return authAttempt;
161
- }
162
- if (authAttempt.status !== 401 && authAttempt.status !== 403) {
163
- // Preserve scope fallback semantics for non-auth failures.
164
- continue;
165
- }
166
- } catch {
167
- // Try the next scope.
168
- }
169
- }
170
-
171
- return firstAttempt;
172
- }
173
-
174
- /**
175
- * Download all file attachments from a Teams message (images, documents, etc.).
176
- * Renamed from downloadMSTeamsImageAttachments to support all file types.
177
- */
178
- export async function downloadMSTeamsAttachments(params: {
179
- attachments: MSTeamsAttachmentLike[] | undefined;
180
- maxBytes: number;
181
- tokenProvider?: MSTeamsAccessTokenProvider;
182
- allowHosts?: string[];
183
- authAllowHosts?: string[];
184
- fetchFn?: typeof fetch;
185
- resolveFn?: MSTeamsAttachmentResolveFn;
186
- /** When true, embeds original filename in stored path for later extraction. */
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;
194
- }): Promise<MSTeamsInboundMedia[]> {
195
- const list = Array.isArray(params.attachments) ? params.attachments : [];
196
- if (list.length === 0) {
197
- return [];
198
- }
199
- const policy = resolveAttachmentFetchPolicy({
200
- allowHosts: params.allowHosts,
201
- authAllowHosts: params.authAllowHosts,
202
- });
203
- const allowHosts = policy.allowHosts;
204
- const ssrfPolicy = resolveMediaSsrfPolicy(allowHosts);
205
-
206
- // Download ANY downloadable attachment (not just images)
207
- const downloadable = list.filter(isDownloadableAttachment);
208
- const candidates: DownloadCandidate[] = downloadable
209
- .map(resolveDownloadCandidate)
210
- .filter(Boolean) as DownloadCandidate[];
211
-
212
- const inlineCandidates = extractInlineImageCandidates(list, {
213
- maxInlineBytes: params.maxBytes,
214
- maxInlineTotalBytes: params.maxBytes,
215
- });
216
-
217
- const seenUrls = new Set<string>();
218
- for (const inline of inlineCandidates) {
219
- if (inline.kind === "url") {
220
- if (!isUrlAllowed(inline.url, allowHosts)) {
221
- continue;
222
- }
223
- if (seenUrls.has(inline.url)) {
224
- continue;
225
- }
226
- seenUrls.add(inline.url);
227
- candidates.push({
228
- url: inline.url,
229
- fileHint: inline.fileHint,
230
- contentTypeHint: inline.contentType,
231
- placeholder: inline.placeholder,
232
- });
233
- }
234
- }
235
- if (candidates.length === 0 && inlineCandidates.length === 0) {
236
- return [];
237
- }
238
-
239
- const out: MSTeamsInboundMedia[] = [];
240
- for (const inline of inlineCandidates) {
241
- if (inline.kind !== "data") {
242
- continue;
243
- }
244
- if (inline.data.byteLength > params.maxBytes) {
245
- continue;
246
- }
247
- try {
248
- // Data inline candidates (base64 data URLs) don't have original filenames
249
- const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(
250
- inline.data,
251
- inline.contentType,
252
- "inbound",
253
- params.maxBytes,
254
- );
255
- out.push({
256
- path: saved.path,
257
- contentType: saved.contentType,
258
- placeholder: inline.placeholder,
259
- });
260
- } catch (err) {
261
- params.logger?.warn?.("msteams inline attachment decode failed", {
262
- error: err instanceof Error ? err.message : String(err),
263
- });
264
- }
265
- }
266
- for (const candidate of candidates) {
267
- if (!isUrlAllowed(candidate.url, allowHosts)) {
268
- continue;
269
- }
270
- try {
271
- const media = await downloadAndStoreMSTeamsRemoteMedia({
272
- url: candidate.url,
273
- filePathHint: candidate.fileHint ?? candidate.url,
274
- maxBytes: params.maxBytes,
275
- contentTypeHint: candidate.contentTypeHint,
276
- placeholder: candidate.placeholder,
277
- preserveFilenames: params.preserveFilenames,
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,
284
- fetchImpl: (input, init) =>
285
- fetchWithAuthFallback({
286
- url: resolveRequestUrl(input),
287
- tokenProvider: params.tokenProvider,
288
- fetchFn: params.fetchFn,
289
- requestInit: init,
290
- resolveFn: params.resolveFn,
291
- policy,
292
- }),
293
- });
294
- out.push(media);
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
- });
300
- }
301
- }
302
- return out;
303
- }
304
-
305
- function safeHostForLog(url: string): string {
306
- try {
307
- return new URL(url).host;
308
- } catch {
309
- return "invalid-url";
310
- }
311
- }