@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,489 +0,0 @@
1
- import { fetchWithSsrFGuard, type SsrFPolicy } from "klaw/plugin-sdk/ssrf-runtime";
2
- import {
3
- normalizeLowercaseStringOrEmpty,
4
- normalizeOptionalLowercaseString,
5
- normalizeOptionalString,
6
- } from "klaw/plugin-sdk/string-coerce-runtime";
7
- import { getMSTeamsRuntime } from "../runtime.js";
8
- import { ensureUserAgentHeader } from "../user-agent.js";
9
- import { downloadMSTeamsAttachments } from "./download.js";
10
- import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
11
- import {
12
- applyAuthorizationHeaderForUrl,
13
- encodeGraphShareId,
14
- GRAPH_ROOT,
15
- estimateBase64DecodedBytes,
16
- inferPlaceholder,
17
- readNestedString,
18
- isUrlAllowed,
19
- type MSTeamsAttachmentDownloadLogger,
20
- type MSTeamsAttachmentFetchPolicy,
21
- type MSTeamsAttachmentResolveFn,
22
- normalizeContentType,
23
- resolveMediaSsrfPolicy,
24
- resolveAttachmentFetchPolicy,
25
- resolveRequestUrl,
26
- safeFetchWithPolicy,
27
- } from "./shared.js";
28
- import type {
29
- MSTeamsAccessTokenProvider,
30
- MSTeamsAttachmentLike,
31
- MSTeamsGraphMediaLogger,
32
- MSTeamsGraphMediaResult,
33
- MSTeamsInboundMedia,
34
- } from "./types.js";
35
-
36
- type GraphHostedContent = {
37
- id?: string | null;
38
- contentType?: string | null;
39
- contentBytes?: string | null;
40
- };
41
-
42
- type GraphAttachment = {
43
- id?: string | null;
44
- contentType?: string | null;
45
- contentUrl?: string | null;
46
- name?: string | null;
47
- thumbnailUrl?: string | null;
48
- content?: unknown;
49
- };
50
-
51
- export function buildMSTeamsGraphMessageUrls(params: {
52
- conversationType?: string | null;
53
- conversationId?: string | null;
54
- messageId?: string | null;
55
- replyToId?: string | null;
56
- conversationMessageId?: string | null;
57
- channelData?: unknown;
58
- }): string[] {
59
- const conversationType = normalizeLowercaseStringOrEmpty(params.conversationType ?? "");
60
- const messageIdCandidates = new Set<string>();
61
- const pushCandidate = (value: string | null | undefined) => {
62
- const trimmed = normalizeOptionalString(value) ?? "";
63
- if (trimmed) {
64
- messageIdCandidates.add(trimmed);
65
- }
66
- };
67
-
68
- pushCandidate(params.messageId);
69
- pushCandidate(params.conversationMessageId);
70
- pushCandidate(readNestedString(params.channelData, ["messageId"]));
71
- pushCandidate(readNestedString(params.channelData, ["teamsMessageId"]));
72
-
73
- const replyToId = normalizeOptionalString(params.replyToId) ?? "";
74
-
75
- if (conversationType === "channel") {
76
- const teamId =
77
- readNestedString(params.channelData, ["team", "id"]) ??
78
- readNestedString(params.channelData, ["teamId"]);
79
- const channelId =
80
- readNestedString(params.channelData, ["channel", "id"]) ??
81
- readNestedString(params.channelData, ["channelId"]) ??
82
- readNestedString(params.channelData, ["teamsChannelId"]);
83
- if (!teamId || !channelId) {
84
- return [];
85
- }
86
- const urls: string[] = [];
87
- if (replyToId) {
88
- for (const candidate of messageIdCandidates) {
89
- if (candidate === replyToId) {
90
- continue;
91
- }
92
- urls.push(
93
- `${GRAPH_ROOT}/teams/${encodeURIComponent(teamId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(replyToId)}/replies/${encodeURIComponent(candidate)}`,
94
- );
95
- }
96
- }
97
- if (messageIdCandidates.size === 0 && replyToId) {
98
- messageIdCandidates.add(replyToId);
99
- }
100
- for (const candidate of messageIdCandidates) {
101
- urls.push(
102
- `${GRAPH_ROOT}/teams/${encodeURIComponent(teamId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(candidate)}`,
103
- );
104
- }
105
- return Array.from(new Set(urls));
106
- }
107
-
108
- const chatId = params.conversationId?.trim() || readNestedString(params.channelData, ["chatId"]);
109
- if (!chatId) {
110
- return [];
111
- }
112
- if (messageIdCandidates.size === 0 && replyToId) {
113
- messageIdCandidates.add(replyToId);
114
- }
115
- const urls = Array.from(messageIdCandidates).map(
116
- (candidate) =>
117
- `${GRAPH_ROOT}/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(candidate)}`,
118
- );
119
- return Array.from(new Set(urls));
120
- }
121
-
122
- async function fetchGraphCollection(params: {
123
- url: string;
124
- accessToken: string;
125
- fetchFn?: typeof fetch;
126
- ssrfPolicy?: SsrFPolicy;
127
- }): Promise<{ status: number; items: unknown[] }> {
128
- const fetchFn = params.fetchFn ?? fetch;
129
- const { response, release } = await fetchWithSsrFGuard({
130
- url: params.url,
131
- fetchImpl: fetchFn,
132
- init: {
133
- headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }),
134
- },
135
- policy: params.ssrfPolicy,
136
- auditContext: "msteams.graph.collection",
137
- });
138
- try {
139
- const status = response.status;
140
- if (!response.ok) {
141
- return { status, items: [] };
142
- }
143
- try {
144
- const data = (await response.json()) as { value?: unknown[] };
145
- return { status, items: Array.isArray(data.value) ? data.value : [] };
146
- } catch {
147
- return { status, items: [] };
148
- }
149
- } finally {
150
- await release();
151
- }
152
- }
153
-
154
- function normalizeGraphAttachment(att: GraphAttachment): MSTeamsAttachmentLike {
155
- let content: unknown = att.content;
156
- if (typeof content === "string") {
157
- try {
158
- content = JSON.parse(content);
159
- } catch {
160
- // Keep as raw string if it's not JSON.
161
- }
162
- }
163
- return {
164
- contentType: normalizeContentType(att.contentType) ?? undefined,
165
- contentUrl: att.contentUrl ?? undefined,
166
- name: att.name ?? undefined,
167
- thumbnailUrl: att.thumbnailUrl ?? undefined,
168
- content,
169
- };
170
- }
171
-
172
- /**
173
- * Download all hosted content from a Teams message (images, documents, etc.).
174
- * Renamed from downloadGraphHostedImages to support all file types.
175
- */
176
- async function downloadGraphHostedContent(params: {
177
- accessToken: string;
178
- messageUrl: string;
179
- maxBytes: number;
180
- fetchFn?: typeof fetch;
181
- preserveFilenames?: boolean;
182
- ssrfPolicy?: SsrFPolicy;
183
- logger?: MSTeamsAttachmentDownloadLogger;
184
- }): Promise<{ media: MSTeamsInboundMedia[]; status: number; count: number }> {
185
- const hosted = (await fetchGraphCollection({
186
- url: `${params.messageUrl}/hostedContents`,
187
- accessToken: params.accessToken,
188
- fetchFn: params.fetchFn,
189
- ssrfPolicy: params.ssrfPolicy,
190
- })) as { status: number; items: GraphHostedContent[] };
191
- if (hosted.items.length === 0) {
192
- return { media: [], status: hosted.status, count: 0 };
193
- }
194
-
195
- const out: MSTeamsInboundMedia[] = [];
196
- for (const item of hosted.items) {
197
- const contentBytes = typeof item.contentBytes === "string" ? item.contentBytes : "";
198
- let buffer: Buffer;
199
- if (contentBytes) {
200
- if (estimateBase64DecodedBytes(contentBytes) > params.maxBytes) {
201
- continue;
202
- }
203
- try {
204
- buffer = Buffer.from(contentBytes, "base64");
205
- } catch (err) {
206
- params.logger?.warn?.("msteams graph hostedContent base64 decode failed", {
207
- error: err instanceof Error ? err.message : String(err),
208
- });
209
- continue;
210
- }
211
- } else if (item.id) {
212
- // contentBytes not inline — fetch from the individual $value endpoint.
213
- try {
214
- const valueUrl = `${params.messageUrl}/hostedContents/${encodeURIComponent(item.id)}/$value`;
215
- const { response: valRes, release } = await fetchWithSsrFGuard({
216
- url: valueUrl,
217
- fetchImpl: params.fetchFn ?? fetch,
218
- init: {
219
- headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }),
220
- },
221
- policy: params.ssrfPolicy,
222
- auditContext: "msteams.graph.hostedContent.value",
223
- });
224
- try {
225
- if (!valRes.ok) {
226
- continue;
227
- }
228
- const saved = await getMSTeamsRuntime().channel.media.saveResponseMedia(valRes, {
229
- sourceUrl: valueUrl,
230
- maxBytes: params.maxBytes,
231
- fallbackContentType: item.contentType ?? undefined,
232
- subdir: "inbound",
233
- });
234
- out.push({
235
- path: saved.path,
236
- contentType: saved.contentType,
237
- placeholder: inferPlaceholder({ contentType: saved.contentType }),
238
- });
239
- } finally {
240
- await release();
241
- }
242
- } catch (err) {
243
- params.logger?.warn?.("msteams graph hostedContent value fetch failed", {
244
- error: err instanceof Error ? err.message : String(err),
245
- });
246
- continue;
247
- }
248
- continue;
249
- } else {
250
- continue;
251
- }
252
- if (buffer.byteLength > params.maxBytes) {
253
- continue;
254
- }
255
- const mime = await getMSTeamsRuntime().media.detectMime({
256
- buffer,
257
- headerMime: item.contentType ?? undefined,
258
- });
259
- // Download any file type, not just images
260
- try {
261
- const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(
262
- buffer,
263
- mime ?? item.contentType ?? undefined,
264
- "inbound",
265
- params.maxBytes,
266
- );
267
- out.push({
268
- path: saved.path,
269
- contentType: saved.contentType,
270
- placeholder: inferPlaceholder({ contentType: saved.contentType }),
271
- });
272
- } catch (err) {
273
- params.logger?.warn?.("msteams graph hostedContent save failed", {
274
- error: err instanceof Error ? err.message : String(err),
275
- });
276
- }
277
- }
278
-
279
- return { media: out, status: hosted.status, count: hosted.items.length };
280
- }
281
-
282
- export async function downloadMSTeamsGraphMedia(params: {
283
- messageUrl?: string | null;
284
- tokenProvider?: MSTeamsAccessTokenProvider;
285
- maxBytes: number;
286
- allowHosts?: string[];
287
- authAllowHosts?: string[];
288
- fetchFn?: typeof fetch;
289
- resolveFn?: MSTeamsAttachmentResolveFn;
290
- /** When true, embeds original filename in stored path for later extraction. */
291
- preserveFilenames?: boolean;
292
- /** Optional logger used to surface Graph/SharePoint fetch errors. */
293
- logger?: MSTeamsAttachmentDownloadLogger;
294
- /** Back-compat diagnostic logger used by older tests/callers. */
295
- log?: MSTeamsGraphMediaLogger;
296
- }): Promise<MSTeamsGraphMediaResult> {
297
- if (!params.messageUrl || !params.tokenProvider) {
298
- return { media: [] };
299
- }
300
- const policy: MSTeamsAttachmentFetchPolicy = resolveAttachmentFetchPolicy({
301
- allowHosts: params.allowHosts,
302
- authAllowHosts: params.authAllowHosts,
303
- });
304
- const ssrfPolicy = resolveMediaSsrfPolicy(policy.allowHosts);
305
- const messageUrl = params.messageUrl;
306
- const debugLog =
307
- params.log ?? (params.logger as MSTeamsGraphMediaLogger | undefined) ?? undefined;
308
- let accessToken: string;
309
- try {
310
- accessToken = await params.tokenProvider.getAccessToken("https://graph.microsoft.com");
311
- } catch (err) {
312
- debugLog?.debug?.("graph media token acquisition failed", {
313
- messageUrl,
314
- error: err instanceof Error ? err.message : String(err),
315
- });
316
- params.logger?.warn?.("msteams graph token acquisition failed", {
317
- error: err instanceof Error ? err.message : String(err),
318
- });
319
- return { media: [], messageUrl, tokenError: true };
320
- }
321
-
322
- const fetchFn = params.fetchFn ?? fetch;
323
- const sharePointMedia: MSTeamsInboundMedia[] = [];
324
- const downloadedReferenceUrls = new Set<string>();
325
- let messageAttachments: GraphAttachment[] = [];
326
- let messageStatus: number | undefined;
327
- try {
328
- const { response: msgRes, release } = await fetchWithSsrFGuard({
329
- url: messageUrl,
330
- fetchImpl: fetchFn,
331
- init: {
332
- headers: ensureUserAgentHeader({ Authorization: `Bearer ${accessToken}` }),
333
- },
334
- policy: ssrfPolicy,
335
- auditContext: "msteams.graph.message",
336
- });
337
- try {
338
- messageStatus = msgRes.status;
339
- if (msgRes.ok) {
340
- let msgData: {
341
- body?: { content?: string; contentType?: string };
342
- attachments?: GraphAttachment[];
343
- };
344
- try {
345
- msgData = (await msgRes.json()) as typeof msgData;
346
- } catch (err) {
347
- debugLog?.debug?.("graph media message parse failed", {
348
- messageUrl,
349
- error: err instanceof Error ? err.message : String(err),
350
- });
351
- params.logger?.warn?.("msteams graph message parse failed", {
352
- error: err instanceof Error ? err.message : String(err),
353
- messageUrl,
354
- });
355
- msgData = {};
356
- }
357
- messageAttachments = Array.isArray(msgData.attachments) ? msgData.attachments : [];
358
-
359
- const spAttachments = messageAttachments.filter(
360
- (a) => a.contentType === "reference" && a.contentUrl && a.name,
361
- );
362
- for (const att of spAttachments) {
363
- const name = att.name ?? "file";
364
- const shareUrl = att.contentUrl ?? "";
365
- if (!shareUrl) {
366
- continue;
367
- }
368
-
369
- try {
370
- const sharesUrl = `${GRAPH_ROOT}/shares/${encodeGraphShareId(shareUrl)}/driveItem/content`;
371
- if (!isUrlAllowed(sharesUrl, policy.allowHosts)) {
372
- debugLog?.debug?.("graph media sharepoint url not in allowHosts", {
373
- messageUrl,
374
- sharesUrl,
375
- });
376
- continue;
377
- }
378
-
379
- const media = await downloadAndStoreMSTeamsRemoteMedia({
380
- url: sharesUrl,
381
- filePathHint: name,
382
- maxBytes: params.maxBytes,
383
- contentTypeHint: "application/octet-stream",
384
- preserveFilenames: params.preserveFilenames,
385
- ssrfPolicy,
386
- useDirectFetch: true,
387
- fetchImpl: async (input, init) => {
388
- const requestUrl = resolveRequestUrl(input);
389
- const headers = ensureUserAgentHeader(init?.headers);
390
- applyAuthorizationHeaderForUrl({
391
- headers,
392
- url: requestUrl,
393
- authAllowHosts: policy.authAllowHosts,
394
- bearerToken: accessToken,
395
- });
396
- return await safeFetchWithPolicy({
397
- url: requestUrl,
398
- policy,
399
- fetchFn,
400
- requestInit: {
401
- ...init,
402
- headers,
403
- },
404
- resolveFn: params.resolveFn,
405
- });
406
- },
407
- });
408
- sharePointMedia.push(media);
409
- downloadedReferenceUrls.add(shareUrl);
410
- } catch (err) {
411
- params.logger?.warn?.("msteams SharePoint reference download failed", {
412
- error: err instanceof Error ? err.message : String(err),
413
- name,
414
- });
415
- }
416
- }
417
- } else {
418
- debugLog?.debug?.("graph media message fetch not ok", {
419
- messageUrl,
420
- status: messageStatus,
421
- });
422
- }
423
- } finally {
424
- await release();
425
- }
426
- } catch (err) {
427
- debugLog?.debug?.("graph media message fetch failed", {
428
- messageUrl,
429
- error: err instanceof Error ? err.message : String(err),
430
- });
431
- params.logger?.warn?.("msteams graph message fetch failed", {
432
- error: err instanceof Error ? err.message : String(err),
433
- });
434
- }
435
-
436
- const hosted = await downloadGraphHostedContent({
437
- accessToken,
438
- messageUrl,
439
- maxBytes: params.maxBytes,
440
- fetchFn: params.fetchFn,
441
- preserveFilenames: params.preserveFilenames,
442
- ssrfPolicy,
443
- logger: params.logger,
444
- });
445
-
446
- const normalizedAttachments = messageAttachments.map(normalizeGraphAttachment);
447
- const filteredAttachments =
448
- sharePointMedia.length > 0
449
- ? normalizedAttachments.filter((att) => {
450
- const contentType = normalizeOptionalLowercaseString(att.contentType);
451
- if (contentType !== "reference") {
452
- return true;
453
- }
454
- const url = typeof att.contentUrl === "string" ? att.contentUrl : "";
455
- if (!url) {
456
- return true;
457
- }
458
- return !downloadedReferenceUrls.has(url);
459
- })
460
- : normalizedAttachments;
461
- let attachmentMedia: MSTeamsInboundMedia[] = [];
462
- try {
463
- attachmentMedia = await downloadMSTeamsAttachments({
464
- attachments: filteredAttachments,
465
- maxBytes: params.maxBytes,
466
- tokenProvider: params.tokenProvider,
467
- allowHosts: policy.allowHosts,
468
- authAllowHosts: policy.authAllowHosts,
469
- fetchFn: params.fetchFn,
470
- resolveFn: params.resolveFn,
471
- preserveFilenames: params.preserveFilenames,
472
- logger: params.logger,
473
- });
474
- } catch (err) {
475
- params.logger?.warn?.("msteams graph attachment download failed", {
476
- error: err instanceof Error ? err.message : String(err),
477
- messageUrl,
478
- });
479
- }
480
-
481
- return {
482
- media: [...sharePointMedia, ...hosted.media, ...attachmentMedia],
483
- hostedCount: hosted.count,
484
- attachmentCount: filteredAttachments.length + sharePointMedia.length,
485
- hostedStatus: hosted.status,
486
- attachmentStatus: messageStatus,
487
- messageUrl,
488
- };
489
- }
@@ -1,122 +0,0 @@
1
- import {
2
- ATTACHMENT_TAG_RE,
3
- extractHtmlFromAttachment,
4
- extractInlineImageCandidates,
5
- IMG_SRC_RE,
6
- isLikelyImageAttachment,
7
- safeHostForUrl,
8
- } from "./shared.js";
9
- import type { MSTeamsAttachmentLike, MSTeamsHtmlAttachmentSummary } from "./types.js";
10
-
11
- /**
12
- * Extract every `<attachment id="...">` reference from the HTML attachments in
13
- * the inbound activity. Returns the complete (non-sliced) list; callers that
14
- * need a capped diagnostic summary can truncate after calling this helper.
15
- */
16
- export function extractMSTeamsHtmlAttachmentIds(
17
- attachments: MSTeamsAttachmentLike[] | undefined,
18
- ): string[] {
19
- const list = Array.isArray(attachments) ? attachments : [];
20
- if (list.length === 0) {
21
- return [];
22
- }
23
- const ids = new Set<string>();
24
- for (const att of list) {
25
- const html = extractHtmlFromAttachment(att);
26
- if (!html) {
27
- continue;
28
- }
29
- ATTACHMENT_TAG_RE.lastIndex = 0;
30
- let match: RegExpExecArray | null = ATTACHMENT_TAG_RE.exec(html);
31
- while (match) {
32
- const id = match[1]?.trim();
33
- if (id) {
34
- ids.add(id);
35
- }
36
- match = ATTACHMENT_TAG_RE.exec(html);
37
- }
38
- }
39
- return Array.from(ids);
40
- }
41
-
42
- export function summarizeMSTeamsHtmlAttachments(
43
- attachments: MSTeamsAttachmentLike[] | undefined,
44
- ): MSTeamsHtmlAttachmentSummary | undefined {
45
- const list = Array.isArray(attachments) ? attachments : [];
46
- if (list.length === 0) {
47
- return undefined;
48
- }
49
- let htmlAttachments = 0;
50
- let imgTags = 0;
51
- let dataImages = 0;
52
- let cidImages = 0;
53
- const srcHosts = new Set<string>();
54
- let attachmentTags = 0;
55
- const attachmentIds = new Set<string>();
56
-
57
- for (const att of list) {
58
- const html = extractHtmlFromAttachment(att);
59
- if (!html) {
60
- continue;
61
- }
62
- htmlAttachments += 1;
63
- IMG_SRC_RE.lastIndex = 0;
64
- let match: RegExpExecArray | null = IMG_SRC_RE.exec(html);
65
- while (match) {
66
- imgTags += 1;
67
- const src = match[1]?.trim();
68
- if (src) {
69
- if (src.startsWith("data:")) {
70
- dataImages += 1;
71
- } else if (src.startsWith("cid:")) {
72
- cidImages += 1;
73
- } else {
74
- srcHosts.add(safeHostForUrl(src));
75
- }
76
- }
77
- match = IMG_SRC_RE.exec(html);
78
- }
79
-
80
- ATTACHMENT_TAG_RE.lastIndex = 0;
81
- let attachmentMatch: RegExpExecArray | null = ATTACHMENT_TAG_RE.exec(html);
82
- while (attachmentMatch) {
83
- attachmentTags += 1;
84
- const id = attachmentMatch[1]?.trim();
85
- if (id) {
86
- attachmentIds.add(id);
87
- }
88
- attachmentMatch = ATTACHMENT_TAG_RE.exec(html);
89
- }
90
- }
91
-
92
- if (htmlAttachments === 0) {
93
- return undefined;
94
- }
95
- return {
96
- htmlAttachments,
97
- imgTags,
98
- dataImages,
99
- cidImages,
100
- srcHosts: Array.from(srcHosts).slice(0, 5),
101
- attachmentTags,
102
- attachmentIds: Array.from(attachmentIds).slice(0, 5),
103
- };
104
- }
105
-
106
- export function buildMSTeamsAttachmentPlaceholder(
107
- attachments: MSTeamsAttachmentLike[] | undefined,
108
- limits?: { maxInlineBytes?: number; maxInlineTotalBytes?: number },
109
- ): string {
110
- const list = Array.isArray(attachments) ? attachments : [];
111
- if (list.length === 0) {
112
- return "";
113
- }
114
- const imageCount = list.filter(isLikelyImageAttachment).length;
115
- const inlineCount = extractInlineImageCandidates(list, limits).length;
116
- const totalImages = imageCount + inlineCount;
117
- if (totalImages > 0) {
118
- return `<media:image>${totalImages > 1 ? ` (${totalImages} images)` : ""}`;
119
- }
120
- const count = list.length;
121
- return `<media:document>${count > 1 ? ` (${count} files)` : ""}`;
122
- }
@@ -1,14 +0,0 @@
1
- import { buildMediaPayload } from "../../runtime-api.js";
2
-
3
- export function buildMSTeamsMediaPayload(
4
- mediaList: Array<{ path: string; contentType?: string }>,
5
- ): {
6
- MediaPath?: string;
7
- MediaType?: string;
8
- MediaUrl?: string;
9
- MediaPaths?: string[];
10
- MediaUrls?: string[];
11
- MediaTypes?: string[];
12
- } {
13
- return buildMediaPayload(mediaList, { preserveMediaTypeCardinality: true });
14
- }