@kodelyth/msteams 2026.5.42 → 2026.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +18 -6
  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,754 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import type { PluginRuntime, SsrFPolicy } from "../runtime-api.js";
3
- import { readRemoteMediaResponse } from "./attachments.test-helpers.js";
4
- import { downloadMSTeamsAttachments } from "./attachments/download.js";
5
- import { resolveRequestUrl } from "./attachments/shared.js";
6
- import { setMSTeamsRuntime } from "./runtime.js";
7
-
8
- const saveResponseMediaMock = vi.hoisted(() =>
9
- vi.fn(async (response: Response) => {
10
- if (!response.ok) {
11
- throw new Error(`HTTP ${response.status}`);
12
- }
13
- const contentType = response.headers.get("content-type") ?? "image/png";
14
- return {
15
- id: contentType === "application/pdf" ? "saved.pdf" : "saved.png",
16
- path: contentType === "application/pdf" ? "/tmp/saved.pdf" : "/tmp/saved.png",
17
- size: 42,
18
- contentType,
19
- };
20
- }),
21
- );
22
-
23
- vi.mock("klaw/plugin-sdk/media-runtime", async () => ({
24
- saveResponseMedia: saveResponseMediaMock,
25
- }));
26
-
27
- const GRAPH_HOST = "graph.microsoft.com";
28
- const AZUREEDGE_HOST = "azureedge.net";
29
- const TEST_HOST = "x";
30
- const createUrlForHost = (host: string, pathSegment: string) => `https://${host}/${pathSegment}`;
31
- const createTestUrl = (pathSegment: string) => createUrlForHost(TEST_HOST, pathSegment);
32
- const SAVED_PNG_PATH = "/tmp/saved.png";
33
- const SAVED_PDF_PATH = "/tmp/saved.pdf";
34
- const TEST_URL_IMAGE = createTestUrl("img");
35
- const TEST_URL_INLINE_IMAGE = createTestUrl("inline.png");
36
- const TEST_URL_DOC_PDF = createTestUrl("doc.pdf");
37
- const TEST_URL_FILE_DOWNLOAD = createTestUrl("dl");
38
- const TEST_URL_OUTSIDE_ALLOWLIST = "https://evil.test/img";
39
- const CONTENT_TYPE_IMAGE_PNG = "image/png";
40
- const CONTENT_TYPE_APPLICATION_PDF = "application/pdf";
41
- const CONTENT_TYPE_APPLICATION_ZIP = "application/zip";
42
- const CONTENT_TYPE_TEXT_HTML = "text/html";
43
- const CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info";
44
- const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
45
- const MAX_REDIRECT_HOPS = 5;
46
- type RemoteMediaFetchParams = {
47
- url: string;
48
- maxBytes?: number;
49
- filePathHint?: string;
50
- ssrfPolicy?: SsrFPolicy;
51
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
52
- };
53
-
54
- const detectMimeDefault = async () => CONTENT_TYPE_IMAGE_PNG;
55
- const saveMediaBufferDefault = async (
56
- _buffer: Buffer,
57
- contentType?: string,
58
- _subdir?: string,
59
- _maxBytes?: number,
60
- _originalFilename?: string,
61
- ) => ({
62
- id: "saved.png",
63
- path: contentType === CONTENT_TYPE_APPLICATION_PDF ? SAVED_PDF_PATH : SAVED_PNG_PATH,
64
- size: Buffer.byteLength(PNG_BUFFER),
65
- contentType: contentType ?? CONTENT_TYPE_IMAGE_PNG,
66
- });
67
- const detectMimeMock = vi.fn(detectMimeDefault);
68
- const saveMediaBufferMock = vi.fn(saveMediaBufferDefault);
69
- function isHostnameAllowedByPattern(hostname: string, pattern: string): boolean {
70
- if (pattern.startsWith("*.")) {
71
- const suffix = pattern.slice(2);
72
- return suffix.length > 0 && hostname !== suffix && hostname.endsWith(`.${suffix}`);
73
- }
74
- return hostname === pattern;
75
- }
76
-
77
- function isUrlAllowedBySsrfPolicy(url: string, policy?: SsrFPolicy): boolean {
78
- if (!policy?.hostnameAllowlist || policy.hostnameAllowlist.length === 0) {
79
- return true;
80
- }
81
- const hostname = new URL(url).hostname.toLowerCase();
82
- return policy.hostnameAllowlist.some((pattern) =>
83
- isHostnameAllowedByPattern(hostname, pattern.toLowerCase()),
84
- );
85
- }
86
-
87
- async function readRemoteMediaBufferWithRedirects(
88
- params: RemoteMediaFetchParams,
89
- requestInit?: RequestInit,
90
- ) {
91
- const fetchFn = params.fetchImpl ?? fetch;
92
- let currentUrl = params.url;
93
- for (let i = 0; i <= MAX_REDIRECT_HOPS; i += 1) {
94
- if (!isUrlAllowedBySsrfPolicy(currentUrl, params.ssrfPolicy)) {
95
- throw new Error(`Blocked hostname (not in allowlist): ${currentUrl}`);
96
- }
97
- const res = await fetchFn(currentUrl, { redirect: "manual", ...requestInit });
98
- if (REDIRECT_STATUS_CODES.has(res.status)) {
99
- const location = res.headers.get("location");
100
- if (!location) {
101
- throw new Error("redirect missing location");
102
- }
103
- currentUrl = new URL(location, currentUrl).toString();
104
- continue;
105
- }
106
- return readRemoteMediaResponse(res, params);
107
- }
108
- throw new Error("too many redirects");
109
- }
110
-
111
- const readRemoteMediaBufferMock = vi.fn(async (params: RemoteMediaFetchParams) => {
112
- return await readRemoteMediaBufferWithRedirects(params);
113
- });
114
- const saveRemoteMediaMock = vi.fn(async (params: RemoteMediaFetchParams) => {
115
- const fetched = await readRemoteMediaBufferWithRedirects(params);
116
- return await saveMediaBufferMock(
117
- fetched.buffer,
118
- fetched.contentType,
119
- "inbound",
120
- params.maxBytes,
121
- params.filePathHint,
122
- );
123
- });
124
-
125
- const runtimeStub = {
126
- media: {
127
- detectMime: detectMimeMock,
128
- },
129
- channel: {
130
- media: {
131
- readRemoteMediaBuffer: readRemoteMediaBufferMock,
132
- saveRemoteMedia: saveRemoteMediaMock,
133
- saveResponseMedia: saveResponseMediaMock,
134
- saveMediaBuffer: saveMediaBufferMock,
135
- },
136
- },
137
- } as unknown as PluginRuntime;
138
-
139
- type DownloadAttachmentsParams = Parameters<typeof downloadMSTeamsAttachments>[0];
140
- type DownloadedMedia = Awaited<ReturnType<typeof downloadMSTeamsAttachments>>;
141
- type DownloadAttachmentsBuildOverrides = Partial<
142
- Omit<DownloadAttachmentsParams, "attachments" | "maxBytes" | "allowHosts">
143
- > &
144
- Pick<DownloadAttachmentsParams, "allowHosts">;
145
- type DownloadAttachmentsNoFetchOverrides = Partial<
146
- Omit<DownloadAttachmentsParams, "attachments" | "maxBytes" | "allowHosts" | "fetchFn">
147
- > &
148
- Pick<DownloadAttachmentsParams, "allowHosts">;
149
- type FetchFn = typeof fetch;
150
- type MSTeamsAttachments = DownloadAttachmentsParams["attachments"];
151
- type LabeledCase = { label: string };
152
- type FetchCallExpectation = { expectFetchCalled?: boolean };
153
- type DownloadedMediaExpectation = { path?: string; placeholder?: string };
154
-
155
- const DEFAULT_MAX_BYTES = 1024 * 1024;
156
- const DEFAULT_ALLOW_HOSTS = [TEST_HOST];
157
- const MEDIA_PLACEHOLDER_IMAGE = "<media:image>";
158
- const MEDIA_PLACEHOLDER_DOCUMENT = "<media:document>";
159
- const formatDocumentPlaceholder = (count: number) =>
160
- count > 1 ? `${MEDIA_PLACEHOLDER_DOCUMENT} (${count} files)` : MEDIA_PLACEHOLDER_DOCUMENT;
161
- const IMAGE_ATTACHMENT = { contentType: CONTENT_TYPE_IMAGE_PNG, contentUrl: TEST_URL_IMAGE };
162
- const PNG_BUFFER = Buffer.from("png");
163
- const PNG_BASE64 = PNG_BUFFER.toString("base64");
164
- const PDF_BUFFER = Buffer.from("pdf");
165
- const createTokenProvider = (
166
- tokenOrResolver: string | ((scope: string) => string | Promise<string>) = "token",
167
- ) => ({
168
- getAccessToken: vi.fn(async (scope: string) =>
169
- typeof tokenOrResolver === "function" ? await tokenOrResolver(scope) : tokenOrResolver,
170
- ),
171
- });
172
- const asSingleItemArray = <T>(value: T) => [value];
173
- const withLabel = <T extends object>(label: string, fields: T): T & LabeledCase => ({
174
- label,
175
- ...fields,
176
- });
177
- const buildAttachment = <T extends Record<string, unknown>>(contentType: string, props: T) => ({
178
- contentType,
179
- ...props,
180
- });
181
- const createHtmlAttachment = (content: string) =>
182
- buildAttachment(CONTENT_TYPE_TEXT_HTML, { content });
183
- const buildHtmlImageTag = (src: string) => `<img src="${src}" />`;
184
- const createHtmlImageAttachments = (sources: string[], prefix = "") =>
185
- asSingleItemArray(createHtmlAttachment(`${prefix}${sources.map(buildHtmlImageTag).join("")}`));
186
- const createContentUrlAttachments = (contentType: string, ...contentUrls: string[]) =>
187
- contentUrls.map((contentUrl) => buildAttachment(contentType, { contentUrl }));
188
- const createImageAttachments = (...contentUrls: string[]) =>
189
- createContentUrlAttachments(CONTENT_TYPE_IMAGE_PNG, ...contentUrls);
190
- const createPdfAttachments = (...contentUrls: string[]) =>
191
- createContentUrlAttachments(CONTENT_TYPE_APPLICATION_PDF, ...contentUrls);
192
- const createTeamsFileDownloadInfoAttachments = (
193
- downloadUrl = TEST_URL_FILE_DOWNLOAD,
194
- fileType = "png",
195
- ) =>
196
- asSingleItemArray(
197
- buildAttachment(CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO, {
198
- content: { downloadUrl, fileType },
199
- }),
200
- );
201
- const createHostedContentsWithType = (contentType: string, ...ids: string[]) =>
202
- ids.map((id) => ({ id, contentType, contentBytes: PNG_BASE64 }));
203
- type BinaryPayload = Uint8Array | string;
204
- const createBufferResponse = (payload: BinaryPayload, contentType: string, status = 200) => {
205
- const raw = typeof payload === "string" ? Buffer.from(payload) : payload;
206
- return new Response(new Uint8Array(raw), {
207
- status,
208
- headers: { "content-type": contentType },
209
- });
210
- };
211
- const createJsonResponse = (payload: unknown, status = 200) =>
212
- new Response(JSON.stringify(payload), { status });
213
- const createTextResponse = (body: string, status = 200) => new Response(body, { status });
214
- const createNotFoundResponse = () => new Response("not found", { status: 404 });
215
- const createRedirectResponse = (location: string, status = 302) =>
216
- new Response(null, { status, headers: { location } });
217
- const publicResolve = async () => ({ address: "13.107.136.10" });
218
-
219
- const createOkFetchMock = (contentType: string, payload = "png") =>
220
- vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
221
- createBufferResponse(payload, contentType),
222
- );
223
- const asFetchFn = (fetchFn: unknown): FetchFn => fetchFn as FetchFn;
224
-
225
- const buildDownloadParams = (
226
- attachments: MSTeamsAttachments,
227
- overrides: DownloadAttachmentsBuildOverrides = {},
228
- ): DownloadAttachmentsParams => {
229
- return {
230
- attachments,
231
- maxBytes: DEFAULT_MAX_BYTES,
232
- allowHosts: DEFAULT_ALLOW_HOSTS,
233
- resolveFn: publicResolve,
234
- ...overrides,
235
- };
236
- };
237
-
238
- const downloadAttachmentsWithFetch = async (
239
- attachments: MSTeamsAttachments,
240
- fetchFn: unknown,
241
- overrides: DownloadAttachmentsNoFetchOverrides = {},
242
- options: FetchCallExpectation = {},
243
- ) => {
244
- const media = await downloadMSTeamsAttachments(
245
- buildDownloadParams(attachments, {
246
- ...overrides,
247
- fetchFn: asFetchFn(fetchFn),
248
- }),
249
- );
250
- expectMockCallState(fetchFn, options.expectFetchCalled ?? true);
251
- return media;
252
- };
253
-
254
- const createAuthAwareImageFetchMock = (params: { unauthStatus: number; unauthBody: string }) =>
255
- vi.fn(async (_url: string, opts?: RequestInit) => {
256
- const headers = new Headers(opts?.headers);
257
- const hasAuth = Boolean(headers.get("Authorization"));
258
- if (!hasAuth) {
259
- return createTextResponse(params.unauthBody, params.unauthStatus);
260
- }
261
- return createBufferResponse(PNG_BUFFER, CONTENT_TYPE_IMAGE_PNG);
262
- });
263
- const expectMockCallState = (mockFn: unknown, shouldCall: boolean) => {
264
- if (shouldCall) {
265
- expect(mockFn).toHaveBeenCalled();
266
- } else {
267
- expect(mockFn).not.toHaveBeenCalled();
268
- }
269
- };
270
-
271
- const firstMockCall = (mock: ReturnType<typeof vi.fn>, label: string): unknown[] => {
272
- const [call] = mock.mock.calls;
273
- if (!call) {
274
- throw new Error(`expected ${label} call`);
275
- }
276
- return call;
277
- };
278
-
279
- const expectAttachmentMediaLength = (media: DownloadedMedia, expectedLength: number) => {
280
- expect(media).toHaveLength(expectedLength);
281
- };
282
- const expectSingleMedia = (media: DownloadedMedia, expected: DownloadedMediaExpectation = {}) => {
283
- expectAttachmentMediaLength(media, 1);
284
- expectFirstMedia(media, expected);
285
- };
286
- const expectMediaBufferSaved = () => {
287
- expect(
288
- saveResponseMediaMock.mock.calls.length + saveMediaBufferMock.mock.calls.length,
289
- ).toBeGreaterThan(0);
290
- };
291
- const expectFirstMedia = (media: DownloadedMedia, expected: DownloadedMediaExpectation) => {
292
- const first = media[0];
293
- if (expected.path !== undefined) {
294
- expect(first?.path).toBe(expected.path);
295
- }
296
- if (expected.placeholder !== undefined) {
297
- expect(first?.placeholder).toBe(expected.placeholder);
298
- }
299
- };
300
- type AttachmentDownloadSuccessCase = LabeledCase & {
301
- attachments: MSTeamsAttachments;
302
- buildFetchFn?: () => unknown;
303
- beforeDownload?: () => void;
304
- assert?: (media: DownloadedMedia) => void;
305
- };
306
- type AttachmentAuthRetryScenario = {
307
- attachmentUrl: string;
308
- unauthStatus: number;
309
- unauthBody: string;
310
- overrides?: Omit<DownloadAttachmentsNoFetchOverrides, "tokenProvider">;
311
- };
312
- type AttachmentAuthRetryCase = LabeledCase & {
313
- scenario: AttachmentAuthRetryScenario;
314
- expectedMediaLength: number;
315
- expectTokenFetch: boolean;
316
- };
317
- const ATTACHMENT_DOWNLOAD_SUCCESS_CASES: AttachmentDownloadSuccessCase[] = [
318
- withLabel("downloads and stores image contentUrl attachments", {
319
- attachments: asSingleItemArray(IMAGE_ATTACHMENT),
320
- assert: (media) => {
321
- expectFirstMedia(media, { path: SAVED_PNG_PATH });
322
- expectMediaBufferSaved();
323
- },
324
- }),
325
- withLabel("supports Teams file.download.info downloadUrl attachments", {
326
- attachments: createTeamsFileDownloadInfoAttachments(),
327
- }),
328
- withLabel("downloads inline image URLs from html attachments", {
329
- attachments: createHtmlImageAttachments([TEST_URL_INLINE_IMAGE]),
330
- }),
331
- withLabel("downloads non-image file attachments (PDF)", {
332
- attachments: createPdfAttachments(TEST_URL_DOC_PDF),
333
- buildFetchFn: () => createOkFetchMock(CONTENT_TYPE_APPLICATION_PDF, "pdf"),
334
- beforeDownload: () => {
335
- detectMimeMock.mockResolvedValueOnce(CONTENT_TYPE_APPLICATION_PDF);
336
- saveMediaBufferMock.mockResolvedValueOnce({
337
- id: "saved.pdf",
338
- path: SAVED_PDF_PATH,
339
- size: Buffer.byteLength(PDF_BUFFER),
340
- contentType: CONTENT_TYPE_APPLICATION_PDF,
341
- });
342
- },
343
- assert: (media) => {
344
- expectSingleMedia(media, {
345
- path: SAVED_PDF_PATH,
346
- placeholder: formatDocumentPlaceholder(1),
347
- });
348
- },
349
- }),
350
- ];
351
- const ATTACHMENT_AUTH_RETRY_CASES: AttachmentAuthRetryCase[] = [
352
- withLabel("retries with auth when the first request is unauthorized", {
353
- scenario: {
354
- attachmentUrl: IMAGE_ATTACHMENT.contentUrl,
355
- unauthStatus: 401,
356
- unauthBody: "unauthorized",
357
- overrides: { authAllowHosts: [TEST_HOST] },
358
- },
359
- expectedMediaLength: 1,
360
- expectTokenFetch: true,
361
- }),
362
- withLabel("skips auth retries when the host is not in auth allowlist", {
363
- scenario: {
364
- attachmentUrl: createUrlForHost(AZUREEDGE_HOST, "img"),
365
- unauthStatus: 403,
366
- unauthBody: "forbidden",
367
- overrides: {
368
- allowHosts: [AZUREEDGE_HOST],
369
- authAllowHosts: [GRAPH_HOST],
370
- },
371
- },
372
- expectedMediaLength: 0,
373
- expectTokenFetch: false,
374
- }),
375
- ];
376
- const runAttachmentDownloadSuccessCase = async ({
377
- attachments,
378
- buildFetchFn,
379
- beforeDownload,
380
- assert,
381
- }: AttachmentDownloadSuccessCase) => {
382
- const fetchFn = (buildFetchFn ?? (() => createOkFetchMock(CONTENT_TYPE_IMAGE_PNG)))();
383
- beforeDownload?.();
384
- const media = await downloadAttachmentsWithFetch(attachments, fetchFn);
385
- expectSingleMedia(media);
386
- assert?.(media);
387
- };
388
- const runAttachmentAuthRetryCase = async ({
389
- scenario,
390
- expectedMediaLength,
391
- expectTokenFetch,
392
- }: AttachmentAuthRetryCase) => {
393
- const tokenProvider = createTokenProvider();
394
- const fetchMock = createAuthAwareImageFetchMock({
395
- unauthStatus: scenario.unauthStatus,
396
- unauthBody: scenario.unauthBody,
397
- });
398
- const media = await downloadAttachmentsWithFetch(
399
- createImageAttachments(scenario.attachmentUrl),
400
- fetchMock,
401
- { tokenProvider, ...scenario.overrides },
402
- );
403
- expectAttachmentMediaLength(media, expectedMediaLength);
404
- expectMockCallState(tokenProvider.getAccessToken, expectTokenFetch);
405
- };
406
-
407
- describe("msteams attachments", () => {
408
- beforeEach(() => {
409
- detectMimeMock.mockReset();
410
- detectMimeMock.mockImplementation(detectMimeDefault);
411
- saveMediaBufferMock.mockReset();
412
- saveMediaBufferMock.mockImplementation(saveMediaBufferDefault);
413
- readRemoteMediaBufferMock.mockClear();
414
- saveRemoteMediaMock.mockClear();
415
- saveResponseMediaMock.mockClear();
416
- setMSTeamsRuntime(runtimeStub);
417
- });
418
-
419
- describe("downloadMSTeamsAttachments", () => {
420
- it.each<AttachmentDownloadSuccessCase>(ATTACHMENT_DOWNLOAD_SUCCESS_CASES)(
421
- "$label",
422
- runAttachmentDownloadSuccessCase,
423
- );
424
-
425
- it("stores inline data:image base64 payloads", async () => {
426
- const media = await downloadMSTeamsAttachments(
427
- buildDownloadParams([
428
- ...createHtmlImageAttachments([`data:image/png;base64,${PNG_BASE64}`]),
429
- ]),
430
- );
431
-
432
- expectSingleMedia(media);
433
- expectMediaBufferSaved();
434
- });
435
-
436
- it("stores every inline data:image base64 payload", async () => {
437
- const media = await downloadMSTeamsAttachments(
438
- buildDownloadParams([
439
- ...createHtmlImageAttachments([
440
- `data:image/png;base64,${PNG_BASE64}`,
441
- `data:image/png;base64,${PNG_BASE64}`,
442
- ]),
443
- ]),
444
- );
445
-
446
- expectAttachmentMediaLength(media, 2);
447
- expect(saveMediaBufferMock).toHaveBeenCalledTimes(2);
448
- });
449
-
450
- it("skips inline data:image payloads whose bytes sniff as non-image", async () => {
451
- detectMimeMock.mockResolvedValueOnce(CONTENT_TYPE_APPLICATION_ZIP);
452
-
453
- const media = await downloadMSTeamsAttachments(
454
- buildDownloadParams([
455
- ...createHtmlImageAttachments([`data:image/png;base64,${PNG_BASE64}`]),
456
- ]),
457
- );
458
-
459
- expectAttachmentMediaLength(media, 0);
460
- expect(saveMediaBufferMock).not.toHaveBeenCalled();
461
- });
462
-
463
- it.each<AttachmentAuthRetryCase>(ATTACHMENT_AUTH_RETRY_CASES)(
464
- "$label",
465
- runAttachmentAuthRetryCase,
466
- );
467
-
468
- it("preserves auth fallback when dispatcher-mode fetch returns a redirect", async () => {
469
- const redirectedUrl = createTestUrl("redirected.png");
470
- const tokenProvider = createTokenProvider();
471
- const fetchMock = vi.fn(async (url: string, opts?: RequestInit) => {
472
- const hasAuth = Boolean(new Headers(opts?.headers).get("Authorization"));
473
- if (url === TEST_URL_IMAGE) {
474
- return hasAuth
475
- ? createRedirectResponse(redirectedUrl)
476
- : createTextResponse("unauthorized", 401);
477
- }
478
- if (url === redirectedUrl) {
479
- return createBufferResponse(PNG_BUFFER, CONTENT_TYPE_IMAGE_PNG);
480
- }
481
- return createNotFoundResponse();
482
- });
483
-
484
- readRemoteMediaBufferMock.mockImplementationOnce(async (params) => {
485
- return await readRemoteMediaBufferWithRedirects(params, {
486
- dispatcher: {},
487
- } as RequestInit);
488
- });
489
-
490
- const media = await downloadAttachmentsWithFetch(
491
- createImageAttachments(TEST_URL_IMAGE),
492
- fetchMock,
493
- { tokenProvider, authAllowHosts: [TEST_HOST] },
494
- );
495
-
496
- expectAttachmentMediaLength(media, 1);
497
- expect(tokenProvider.getAccessToken).toHaveBeenCalledOnce();
498
- expect(fetchMock.mock.calls.map(([calledUrl]) => calledUrl)).toContain(redirectedUrl);
499
- });
500
-
501
- it("continues scope fallback after non-auth failure and succeeds on later scope", async () => {
502
- let authAttempt = 0;
503
- const tokenProvider = createTokenProvider((scope) => `token:${scope}`);
504
- const fetchMock = vi.fn(async (_url: string, opts?: RequestInit) => {
505
- const auth = new Headers(opts?.headers).get("Authorization");
506
- if (!auth) {
507
- return createTextResponse("unauthorized", 401);
508
- }
509
- authAttempt += 1;
510
- if (authAttempt === 1) {
511
- return createTextResponse("upstream transient", 500);
512
- }
513
- return createBufferResponse(PNG_BUFFER, CONTENT_TYPE_IMAGE_PNG);
514
- });
515
-
516
- const media = await downloadAttachmentsWithFetch(
517
- createImageAttachments(TEST_URL_IMAGE),
518
- fetchMock,
519
- { tokenProvider, authAllowHosts: [TEST_HOST] },
520
- );
521
-
522
- expectAttachmentMediaLength(media, 1);
523
- expect(tokenProvider.getAccessToken).toHaveBeenCalledTimes(2);
524
- });
525
-
526
- it("does not forward Authorization to redirects outside auth allowlist", async () => {
527
- const tokenProvider = createTokenProvider("top-secret-token");
528
- const graphFileUrl = createUrlForHost(GRAPH_HOST, "file");
529
- const seen: Array<{ url: string; auth: string }> = [];
530
- const fetchMock = vi.fn(async (url: string, opts?: RequestInit) => {
531
- const auth = new Headers(opts?.headers).get("Authorization") ?? "";
532
- seen.push({ url, auth });
533
- if (url === graphFileUrl && !auth) {
534
- return new Response("unauthorized", { status: 401 });
535
- }
536
- if (url === graphFileUrl && auth) {
537
- return new Response("", {
538
- status: 302,
539
- headers: { location: "https://attacker.azureedge.net/collect" },
540
- });
541
- }
542
- if (url === "https://attacker.azureedge.net/collect") {
543
- return new Response(Buffer.from("png"), {
544
- status: 200,
545
- headers: { "content-type": CONTENT_TYPE_IMAGE_PNG },
546
- });
547
- }
548
- return createNotFoundResponse();
549
- });
550
-
551
- const media = await downloadMSTeamsAttachments(
552
- buildDownloadParams([{ contentType: CONTENT_TYPE_IMAGE_PNG, contentUrl: graphFileUrl }], {
553
- tokenProvider,
554
- allowHosts: [GRAPH_HOST, AZUREEDGE_HOST],
555
- authAllowHosts: [GRAPH_HOST],
556
- fetchFn: asFetchFn(fetchMock),
557
- }),
558
- );
559
-
560
- expectSingleMedia(media);
561
- const redirected = seen.find(
562
- (entry) => entry.url === "https://attacker.azureedge.net/collect",
563
- );
564
- if (!redirected) {
565
- throw new Error("expected Azure CDN redirect request to be observed");
566
- }
567
- expect(redirected.auth).toBe("");
568
- });
569
-
570
- it("skips urls outside the allowlist", async () => {
571
- const fetchMock = vi.fn();
572
- const media = await downloadAttachmentsWithFetch(
573
- createImageAttachments(TEST_URL_OUTSIDE_ALLOWLIST),
574
- fetchMock,
575
- {
576
- allowHosts: [GRAPH_HOST],
577
- },
578
- { expectFetchCalled: false },
579
- );
580
-
581
- expectAttachmentMediaLength(media, 0);
582
- });
583
-
584
- it("blocks redirects to non-https URLs", async () => {
585
- const insecureUrl = "http://x/insecure.png";
586
- const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
587
- const url = resolveRequestUrl(input);
588
- if (url === TEST_URL_IMAGE) {
589
- return createRedirectResponse(insecureUrl);
590
- }
591
- if (url === insecureUrl) {
592
- return createBufferResponse("insecure", CONTENT_TYPE_IMAGE_PNG);
593
- }
594
- return createNotFoundResponse();
595
- });
596
-
597
- const media = await downloadAttachmentsWithFetch(
598
- createImageAttachments(TEST_URL_IMAGE),
599
- fetchMock,
600
- {
601
- allowHosts: [TEST_HOST],
602
- },
603
- );
604
-
605
- expectAttachmentMediaLength(media, 0);
606
- expect(fetchMock).toHaveBeenCalledTimes(1);
607
- });
608
-
609
- describe("OneDrive/SharePoint shared links", () => {
610
- const GRAPH_SHARES_URL_PREFIX = `https://${GRAPH_HOST}/v1.0/shares/`;
611
- const DEFAULT_GRAPH_ALLOW_HOSTS = [GRAPH_HOST];
612
- const PDF_PAYLOAD = Buffer.from("pdf-bytes");
613
-
614
- const createGraphSharesFetchMock = () =>
615
- vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
616
- const url = resolveRequestUrl(input);
617
- const auth = new Headers(init?.headers).get("Authorization");
618
- if (url.startsWith(GRAPH_SHARES_URL_PREFIX)) {
619
- if (!auth) {
620
- return createTextResponse("unauthorized", 401);
621
- }
622
- return createBufferResponse(PDF_PAYLOAD, CONTENT_TYPE_APPLICATION_PDF);
623
- }
624
- return createNotFoundResponse();
625
- });
626
-
627
- it.each([
628
- {
629
- label: "SharePoint URL",
630
- contentUrl: "https://contoso.sharepoint.com/personal/user/Documents/report.pdf",
631
- },
632
- {
633
- label: "OneDrive 1drv.ms URL",
634
- contentUrl: "https://1drv.ms/b/s!AkxYabcdefg",
635
- },
636
- {
637
- label: "OneDrive onedrive.live.com URL",
638
- contentUrl: "https://onedrive.live.com/share/file",
639
- },
640
- ])("routes $label through Graph shares endpoint", async ({ contentUrl }) => {
641
- const tokenProvider = createTokenProvider();
642
- const fetchMock = createGraphSharesFetchMock();
643
- detectMimeMock.mockResolvedValueOnce(CONTENT_TYPE_APPLICATION_PDF);
644
- saveMediaBufferMock.mockResolvedValueOnce({
645
- id: "saved.pdf",
646
- path: SAVED_PDF_PATH,
647
- size: Buffer.byteLength(PDF_PAYLOAD),
648
- contentType: CONTENT_TYPE_APPLICATION_PDF,
649
- });
650
-
651
- const media = await downloadMSTeamsAttachments(
652
- buildDownloadParams(
653
- [
654
- {
655
- contentType: "reference",
656
- contentUrl,
657
- name: "report.pdf",
658
- },
659
- ],
660
- {
661
- tokenProvider,
662
- allowHosts: DEFAULT_GRAPH_ALLOW_HOSTS,
663
- authAllowHosts: DEFAULT_GRAPH_ALLOW_HOSTS,
664
- fetchFn: asFetchFn(fetchMock),
665
- },
666
- ),
667
- );
668
-
669
- expectAttachmentMediaLength(media, 1);
670
- expect(media[0]?.path).toBe(SAVED_PDF_PATH);
671
- // The only host that should be fetched is graph.microsoft.com.
672
- const calledUrls = (fetchMock.mock.calls as Array<[RequestInfo | URL, RequestInit?]>).map(
673
- ([input]) => resolveRequestUrl(input),
674
- );
675
- expect(calledUrls.length).toBeGreaterThan(0);
676
- for (const url of calledUrls) {
677
- expect(url.startsWith(GRAPH_SHARES_URL_PREFIX)).toBe(true);
678
- }
679
- // Graph scope token was acquired for the shares fetch.
680
- expect(tokenProvider.getAccessToken).toHaveBeenCalled();
681
- });
682
-
683
- it("falls through to direct fetch for non-shared-link URLs", async () => {
684
- const directUrl = createTestUrl("direct.pdf");
685
- const fetchMock = createOkFetchMock(CONTENT_TYPE_APPLICATION_PDF, "pdf");
686
- detectMimeMock.mockResolvedValueOnce(CONTENT_TYPE_APPLICATION_PDF);
687
- saveMediaBufferMock.mockResolvedValueOnce({
688
- id: "saved.pdf",
689
- path: SAVED_PDF_PATH,
690
- size: Buffer.byteLength(PDF_BUFFER),
691
- contentType: CONTENT_TYPE_APPLICATION_PDF,
692
- });
693
-
694
- const media = await downloadAttachmentsWithFetch(
695
- createPdfAttachments(directUrl),
696
- fetchMock,
697
- );
698
-
699
- expectAttachmentMediaLength(media, 1);
700
- const calledUrls = (fetchMock.mock.calls as unknown[]).map((call) => {
701
- const input = (call as [RequestInfo | URL])[0];
702
- return resolveRequestUrl(input);
703
- });
704
- // Should have hit the original host, NOT graph shares.
705
- expect(calledUrls).toContain(directUrl);
706
- expect(calledUrls.filter((url) => url.startsWith(GRAPH_SHARES_URL_PREFIX))).toEqual([]);
707
- });
708
- });
709
-
710
- describe("error logging (issue #63396)", () => {
711
- // Before this fix, fetch failures were swallowed by empty `catch {}`
712
- // blocks, leaving operators with no signal that SharePoint downloads
713
- // were silently failing on Node 24+. These tests pin the logger contract
714
- // so the regression cannot return.
715
- it("invokes logger.warn when a remote media download fails", async () => {
716
- const logger = { warn: vi.fn(), error: vi.fn() };
717
- const fetchMock = vi.fn(async () => createTextResponse("server error", 500));
718
-
719
- const media = await downloadMSTeamsAttachments(
720
- buildDownloadParams(createImageAttachments(TEST_URL_IMAGE), {
721
- fetchFn: asFetchFn(fetchMock),
722
- logger,
723
- }),
724
- );
725
-
726
- expectAttachmentMediaLength(media, 0);
727
- expect(logger.warn).toHaveBeenCalledTimes(1);
728
- expect(firstMockCall(logger.warn, "logger.warn")).toStrictEqual([
729
- "msteams attachment download failed",
730
- {
731
- error: "HTTP 500",
732
- host: "x",
733
- },
734
- ]);
735
- });
736
-
737
- it("does not log when downloads succeed", async () => {
738
- const logger = { warn: vi.fn(), error: vi.fn() };
739
- const fetchMock = createOkFetchMock(CONTENT_TYPE_IMAGE_PNG);
740
-
741
- const media = await downloadMSTeamsAttachments(
742
- buildDownloadParams(createImageAttachments(TEST_URL_IMAGE), {
743
- fetchFn: asFetchFn(fetchMock),
744
- logger,
745
- }),
746
- );
747
-
748
- expectAttachmentMediaLength(media, 1);
749
- expect(logger.warn).not.toHaveBeenCalled();
750
- expect(logger.error).not.toHaveBeenCalled();
751
- });
752
- });
753
- });
754
- });