@kodelyth/msteams 2026.5.42 → 2026.6.1

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