@kodelyth/msteams 2026.5.39 → 2026.5.42

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