@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,414 +0,0 @@
1
- import { mockPinnedHostnameResolution } from "klaw/plugin-sdk/test-env";
2
- import { beforeEach, describe, expect, it, vi } from "vitest";
3
- import type { PluginRuntime } from "../runtime-api.js";
4
- import { readRemoteMediaResponse } from "./attachments.test-helpers.js";
5
- import { downloadMSTeamsGraphMedia } from "./attachments/graph.js";
6
- import { encodeGraphShareId, resolveRequestUrl } from "./attachments/shared.js";
7
- import { setMSTeamsRuntime } from "./runtime.js";
8
-
9
- const GRAPH_HOST = "graph.microsoft.com";
10
- const SHAREPOINT_HOST = "contoso.sharepoint.com";
11
- const DEFAULT_MESSAGE_URL = `https://${GRAPH_HOST}/v1.0/chats/19%3Achat/messages/123`;
12
- const GRAPH_SHARES_URL_PREFIX = `https://${GRAPH_HOST}/v1.0/shares/`;
13
- const DEFAULT_MAX_BYTES = 1024 * 1024;
14
- const DEFAULT_SHAREPOINT_ALLOW_HOSTS = [GRAPH_HOST, SHAREPOINT_HOST];
15
- const DEFAULT_SHARE_REFERENCE_URL = `https://${SHAREPOINT_HOST}/site/file`;
16
- const CONTENT_TYPE_IMAGE_PNG = "image/png";
17
- const CONTENT_TYPE_APPLICATION_PDF = "application/pdf";
18
- const PNG_BUFFER = Buffer.from("png");
19
-
20
- const detectMimeMock = vi.fn(async () => CONTENT_TYPE_IMAGE_PNG);
21
- const saveMediaBufferMock = vi.fn(
22
- async (
23
- _buffer: Buffer,
24
- contentType?: string,
25
- _subdir?: string,
26
- _maxBytes?: number,
27
- _originalFilename?: string,
28
- ) => ({
29
- id: "saved.png",
30
- path: "/tmp/saved.png",
31
- size: Buffer.byteLength(PNG_BUFFER),
32
- contentType: contentType ?? CONTENT_TYPE_IMAGE_PNG,
33
- }),
34
- );
35
- const readRemoteMediaBufferMock = vi.fn(
36
- async (params: {
37
- url: string;
38
- maxBytes?: number;
39
- filePathHint?: string;
40
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
41
- }) => {
42
- const fetchFn = params.fetchImpl ?? fetch;
43
- const res = await fetchFn(params.url, { redirect: "manual" });
44
- return readRemoteMediaResponse(res, params);
45
- },
46
- );
47
- const saveRemoteMediaMock = vi.fn(
48
- async (params: {
49
- url: string;
50
- maxBytes?: number;
51
- filePathHint?: string;
52
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
53
- }) => {
54
- const fetched = await readRemoteMediaBufferMock(params);
55
- return await saveMediaBufferMock(
56
- fetched.buffer,
57
- fetched.contentType,
58
- "inbound",
59
- params.maxBytes,
60
- params.filePathHint,
61
- );
62
- },
63
- );
64
- const saveResponseMediaMock = vi.fn(
65
- async (
66
- res: Response,
67
- options: {
68
- maxBytes?: number;
69
- fallbackContentType?: string;
70
- subdir?: string;
71
- originalFilename?: string;
72
- },
73
- ) => {
74
- const buffer = Buffer.from(await res.arrayBuffer());
75
- return await saveMediaBufferMock(
76
- buffer,
77
- options.fallbackContentType,
78
- options.subdir ?? "inbound",
79
- options.maxBytes,
80
- options.originalFilename,
81
- );
82
- },
83
- );
84
-
85
- const runtimeStub = {
86
- media: {
87
- detectMime: detectMimeMock,
88
- },
89
- channel: {
90
- media: {
91
- readRemoteMediaBuffer: readRemoteMediaBufferMock,
92
- saveRemoteMedia: saveRemoteMediaMock,
93
- saveResponseMedia: saveResponseMediaMock,
94
- saveMediaBuffer: saveMediaBufferMock,
95
- },
96
- },
97
- } as unknown as PluginRuntime;
98
-
99
- type DownloadGraphMediaParams = Parameters<typeof downloadMSTeamsGraphMedia>[0];
100
- type DownloadGraphMediaOverrides = Partial<
101
- Omit<DownloadGraphMediaParams, "messageUrl" | "tokenProvider">
102
- >;
103
- type FetchFn = typeof fetch;
104
- type LabeledCase = { label: string };
105
- type GraphFetchMockOptions = {
106
- hostedContents?: unknown[];
107
- attachments?: unknown[];
108
- messageAttachments?: unknown[];
109
- onShareRequest?: (url: string) => Response | Promise<Response>;
110
- onUnhandled?: (url: string) => Response | Promise<Response> | undefined;
111
- };
112
- type GraphMediaDownloadResult = {
113
- fetchMock: ReturnType<typeof createGraphFetchMock>;
114
- media: Awaited<ReturnType<typeof downloadMSTeamsGraphMedia>>;
115
- };
116
- type GraphMediaSuccessCase = LabeledCase & {
117
- buildOptions: () => GraphFetchMockOptions;
118
- expectedLength: number;
119
- assert?: (params: GraphMediaDownloadResult) => void;
120
- };
121
-
122
- const withLabel = <T extends object>(label: string, fields: T): T & LabeledCase => ({
123
- label,
124
- ...fields,
125
- });
126
- const createTokenProvider = (
127
- tokenOrResolver: string | ((scope: string) => string | Promise<string>) = "token",
128
- ) => ({
129
- getAccessToken: vi.fn(async (scope: string) =>
130
- typeof tokenOrResolver === "function" ? await tokenOrResolver(scope) : tokenOrResolver,
131
- ),
132
- });
133
- const resolvePublicHost = async (): Promise<{ address: string }> => ({ address: "93.184.216.34" });
134
- const createBufferResponse = (payload: Buffer | string, contentType: string, status = 200) => {
135
- const raw = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
136
- return new Response(new Uint8Array(raw), {
137
- status,
138
- headers: { "content-type": contentType },
139
- });
140
- };
141
- const createPdfResponse = (payload: Buffer | string = Buffer.from("pdf")) =>
142
- createBufferResponse(payload, CONTENT_TYPE_APPLICATION_PDF);
143
- const createJsonResponse = (payload: unknown, status = 200) =>
144
- new Response(JSON.stringify(payload), { status });
145
- const createGraphCollectionResponse = (value: unknown[]) => createJsonResponse({ value });
146
- const createNotFoundResponse = () => new Response("not found", { status: 404 });
147
- const createRedirectResponse = (location: string, status = 302) =>
148
- new Response(null, { status, headers: { location } });
149
- const asFetchFn = (fetchFn: unknown): FetchFn => fetchFn as FetchFn;
150
- const expectAttachmentMediaLength = (
151
- media: Awaited<ReturnType<typeof downloadMSTeamsGraphMedia>>["media"],
152
- expectedLength: number,
153
- ) => {
154
- expect(media).toHaveLength(expectedLength);
155
- };
156
- const expectMediaBufferSaved = () => {
157
- expect(saveMediaBufferMock).toHaveBeenCalled();
158
- };
159
-
160
- const createHostedContentsWithType = (contentType: string, ...ids: string[]) =>
161
- ids.map((id) => ({ id, contentType, contentBytes: PNG_BUFFER.toString("base64") }));
162
- const createHostedImageContents = (...ids: string[]) =>
163
- createHostedContentsWithType(CONTENT_TYPE_IMAGE_PNG, ...ids);
164
- const createReferenceAttachment = (shareUrl = DEFAULT_SHARE_REFERENCE_URL) => ({
165
- id: "ref-1",
166
- contentType: "reference",
167
- contentUrl: shareUrl,
168
- name: "report.pdf",
169
- });
170
- const buildShareReferenceGraphFetchOptions = (params: {
171
- referenceAttachment: ReturnType<typeof createReferenceAttachment>;
172
- onShareRequest?: GraphFetchMockOptions["onShareRequest"];
173
- onUnhandled?: GraphFetchMockOptions["onUnhandled"];
174
- }) => ({
175
- attachments: [params.referenceAttachment],
176
- messageAttachments: [params.referenceAttachment],
177
- ...(params.onShareRequest ? { onShareRequest: params.onShareRequest } : {}),
178
- ...(params.onUnhandled ? { onUnhandled: params.onUnhandled } : {}),
179
- });
180
- const buildDefaultShareReferenceGraphFetchOptions = (
181
- params: Omit<Parameters<typeof buildShareReferenceGraphFetchOptions>[0], "referenceAttachment">,
182
- ) =>
183
- buildShareReferenceGraphFetchOptions({
184
- referenceAttachment: createReferenceAttachment(),
185
- ...params,
186
- });
187
- type GraphEndpointResponseHandler = {
188
- suffix: string;
189
- buildResponse: () => Response;
190
- };
191
- const createGraphEndpointResponseHandlers = (params: {
192
- hostedContents: unknown[];
193
- attachments: unknown[];
194
- messageAttachments: unknown[];
195
- }): GraphEndpointResponseHandler[] => [
196
- {
197
- suffix: "/hostedContents",
198
- buildResponse: () => createGraphCollectionResponse(params.hostedContents),
199
- },
200
- {
201
- suffix: "/attachments",
202
- buildResponse: () => createGraphCollectionResponse(params.attachments),
203
- },
204
- {
205
- suffix: "/messages/123",
206
- buildResponse: () => createJsonResponse({ attachments: params.messageAttachments }),
207
- },
208
- ];
209
- const resolveGraphEndpointResponse = (
210
- url: string,
211
- handlers: GraphEndpointResponseHandler[],
212
- ): Response | undefined => {
213
- const handler = handlers.find((entry) => url.endsWith(entry.suffix));
214
- return handler ? handler.buildResponse() : undefined;
215
- };
216
-
217
- const createGraphFetchMock = (options: GraphFetchMockOptions = {}) => {
218
- const hostedContents = options.hostedContents ?? [];
219
- const attachments = options.attachments ?? [];
220
- const messageAttachments = options.messageAttachments ?? [];
221
- const endpointHandlers = createGraphEndpointResponseHandlers({
222
- hostedContents,
223
- attachments,
224
- messageAttachments,
225
- });
226
- return vi.fn(async (url: string) => {
227
- const endpointResponse = resolveGraphEndpointResponse(url, endpointHandlers);
228
- if (endpointResponse) {
229
- return endpointResponse;
230
- }
231
- if (url.startsWith(GRAPH_SHARES_URL_PREFIX) && options.onShareRequest) {
232
- return options.onShareRequest(url);
233
- }
234
- const unhandled = options.onUnhandled ? await options.onUnhandled(url) : undefined;
235
- return unhandled ?? createNotFoundResponse();
236
- });
237
- };
238
- const downloadGraphMediaWithMockOptions = async (
239
- options: GraphFetchMockOptions = {},
240
- overrides: DownloadGraphMediaOverrides = {},
241
- ): Promise<GraphMediaDownloadResult> => {
242
- const fetchMock = createGraphFetchMock(options);
243
- const media = await downloadMSTeamsGraphMedia({
244
- messageUrl: DEFAULT_MESSAGE_URL,
245
- tokenProvider: createTokenProvider(),
246
- maxBytes: DEFAULT_MAX_BYTES,
247
- fetchFn: asFetchFn(fetchMock),
248
- resolveFn: resolvePublicHost,
249
- ...overrides,
250
- });
251
- return { fetchMock, media };
252
- };
253
- const runGraphMediaSuccessCase = async ({
254
- buildOptions,
255
- expectedLength,
256
- assert,
257
- }: GraphMediaSuccessCase) => {
258
- const { fetchMock, media } = await downloadGraphMediaWithMockOptions(buildOptions());
259
- expectAttachmentMediaLength(media.media, expectedLength);
260
- assert?.({ fetchMock, media });
261
- };
262
-
263
- const GRAPH_MEDIA_SUCCESS_CASES: GraphMediaSuccessCase[] = [
264
- withLabel("downloads hostedContents images", {
265
- buildOptions: () => ({ hostedContents: createHostedImageContents("1") }),
266
- expectedLength: 1,
267
- assert: ({ fetchMock }) => {
268
- expect(fetchMock).toHaveBeenCalled();
269
- expectMediaBufferSaved();
270
- },
271
- }),
272
- withLabel("streams hostedContent value responses through shared response saver", {
273
- buildOptions: () => ({
274
- hostedContents: [{ id: "hosted-1", contentType: CONTENT_TYPE_APPLICATION_PDF }],
275
- onUnhandled: (url) =>
276
- url.endsWith("/hostedContents/hosted-1/$value") ? createPdfResponse() : undefined,
277
- }),
278
- expectedLength: 1,
279
- assert: () => {
280
- expect(saveResponseMediaMock).toHaveBeenCalledTimes(1);
281
- expectMediaBufferSaved();
282
- },
283
- }),
284
- withLabel("merges SharePoint reference attachments with hosted content", {
285
- buildOptions: () => {
286
- return {
287
- hostedContents: createHostedImageContents("hosted-1"),
288
- ...buildDefaultShareReferenceGraphFetchOptions({
289
- onShareRequest: () => createPdfResponse(),
290
- }),
291
- };
292
- },
293
- expectedLength: 2,
294
- }),
295
- ];
296
-
297
- describe("msteams graph attachments", () => {
298
- let ssrfMock: { mockRestore: () => void } | undefined;
299
-
300
- beforeEach(() => {
301
- ssrfMock?.mockRestore();
302
- ssrfMock = mockPinnedHostnameResolution();
303
- detectMimeMock.mockClear();
304
- readRemoteMediaBufferMock.mockClear();
305
- saveRemoteMediaMock.mockClear();
306
- saveResponseMediaMock.mockClear();
307
- saveMediaBufferMock.mockClear();
308
- setMSTeamsRuntime(runtimeStub);
309
- });
310
-
311
- it.each<GraphMediaSuccessCase>(GRAPH_MEDIA_SUCCESS_CASES)("$label", runGraphMediaSuccessCase);
312
-
313
- it("does not forward Authorization for SharePoint redirects outside auth allowlist", async () => {
314
- const tokenProvider = createTokenProvider("top-secret-token");
315
- const escapedUrl = "https://example.com/collect";
316
- const seen: Array<{ url: string; auth: string }> = [];
317
- const referenceAttachment = createReferenceAttachment();
318
- const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
319
- const url = resolveRequestUrl(input);
320
- const auth = new Headers(init?.headers).get("Authorization") ?? "";
321
- seen.push({ url, auth });
322
-
323
- if (url === DEFAULT_MESSAGE_URL) {
324
- return createJsonResponse({ attachments: [referenceAttachment] });
325
- }
326
- if (url === `${DEFAULT_MESSAGE_URL}/hostedContents`) {
327
- return createGraphCollectionResponse([]);
328
- }
329
- if (url === `${DEFAULT_MESSAGE_URL}/attachments`) {
330
- return createGraphCollectionResponse([referenceAttachment]);
331
- }
332
- if (url.startsWith(GRAPH_SHARES_URL_PREFIX)) {
333
- return createRedirectResponse(escapedUrl);
334
- }
335
- if (url === escapedUrl) {
336
- return createPdfResponse();
337
- }
338
- return createNotFoundResponse();
339
- });
340
-
341
- const media = await downloadMSTeamsGraphMedia({
342
- messageUrl: DEFAULT_MESSAGE_URL,
343
- tokenProvider,
344
- maxBytes: DEFAULT_MAX_BYTES,
345
- allowHosts: [...DEFAULT_SHAREPOINT_ALLOW_HOSTS, "example.com"],
346
- authAllowHosts: DEFAULT_SHAREPOINT_ALLOW_HOSTS,
347
- fetchFn: asFetchFn(fetchMock),
348
- resolveFn: resolvePublicHost,
349
- });
350
-
351
- expectAttachmentMediaLength(media.media, 1);
352
- const redirected = seen.find((entry) => entry.url === escapedUrl);
353
- if (!redirected) {
354
- throw new Error("expected SharePoint redirect request to be observed");
355
- }
356
- expect(redirected.auth).toBe("");
357
- });
358
-
359
- it("blocks SharePoint redirects to hosts outside allowHosts", async () => {
360
- const escapedUrl = "https://evil.example/internal.pdf";
361
- const { fetchMock, media } = await downloadGraphMediaWithMockOptions(
362
- {
363
- ...buildDefaultShareReferenceGraphFetchOptions({
364
- onShareRequest: () => createRedirectResponse(escapedUrl),
365
- onUnhandled: (url) => {
366
- if (url === escapedUrl) {
367
- return createPdfResponse("should-not-be-fetched");
368
- }
369
- return undefined;
370
- },
371
- }),
372
- },
373
- {
374
- allowHosts: DEFAULT_SHAREPOINT_ALLOW_HOSTS,
375
- },
376
- );
377
-
378
- expectAttachmentMediaLength(media.media, 0);
379
- const calledUrls = fetchMock.mock.calls.map((call) => call[0]);
380
- const expectedSharesUrl = `${GRAPH_SHARES_URL_PREFIX}${encodeGraphShareId(DEFAULT_SHARE_REFERENCE_URL)}/driveItem/content`;
381
- expect(calledUrls).toEqual([
382
- DEFAULT_MESSAGE_URL,
383
- expectedSharesUrl,
384
- `${DEFAULT_MESSAGE_URL}/hostedContents`,
385
- expectedSharesUrl,
386
- ]);
387
- expect(calledUrls).not.toContain(escapedUrl);
388
- });
389
-
390
- it("skips inline hosted content when estimated decoded bytes exceed maxBytes", async () => {
391
- const oversizedBase64 = "A".repeat(16);
392
- const bufferFromSpy = vi.spyOn(Buffer, "from");
393
-
394
- try {
395
- const { media } = await downloadGraphMediaWithMockOptions(
396
- {
397
- hostedContents: [
398
- {
399
- id: "hosted-oversized",
400
- contentType: CONTENT_TYPE_IMAGE_PNG,
401
- contentBytes: oversizedBase64,
402
- },
403
- ],
404
- },
405
- { maxBytes: 4 },
406
- );
407
-
408
- expect(media.media).toStrictEqual([]);
409
- expect(bufferFromSpy).not.toHaveBeenCalledWith(oversizedBase64, "base64");
410
- } finally {
411
- bufferFromSpy.mockRestore();
412
- }
413
- });
414
- });
@@ -1,245 +0,0 @@
1
- import { beforeEach, describe, expect, it } from "vitest";
2
- import type { PluginRuntime } from "../runtime-api.js";
3
- import {
4
- buildMSTeamsAttachmentPlaceholder,
5
- buildMSTeamsGraphMessageUrls,
6
- buildMSTeamsMediaPayload,
7
- } from "./attachments.js";
8
- import { setMSTeamsRuntime } from "./runtime.js";
9
-
10
- const SHAREPOINT_HOST = "contoso.sharepoint.com";
11
- const TEST_HOST = "x";
12
- const createUrlForHost = (host: string, pathSegment: string) => `https://${host}/${pathSegment}`;
13
- const createTestUrl = (pathSegment: string) => createUrlForHost(TEST_HOST, pathSegment);
14
- const TEST_URL_IMAGE = createTestUrl("img");
15
- const TEST_URL_IMAGE_PNG = createTestUrl("img.png");
16
- const TEST_URL_IMAGE_1_PNG = createTestUrl("1.png");
17
- const TEST_URL_IMAGE_2_JPG = createTestUrl("2.jpg");
18
- const TEST_URL_PDF = createTestUrl("x.pdf");
19
- const TEST_URL_PDF_1 = createTestUrl("1.pdf");
20
- const TEST_URL_PDF_2 = createTestUrl("2.pdf");
21
- const TEST_URL_HTML_A = createTestUrl("a.png");
22
- const TEST_URL_HTML_B = createTestUrl("b.png");
23
- const CONTENT_TYPE_IMAGE_PNG = "image/png";
24
- const CONTENT_TYPE_APPLICATION_PDF = "application/pdf";
25
- const CONTENT_TYPE_TEXT_HTML = "text/html";
26
- const CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info";
27
- type AttachmentPlaceholderInput = Parameters<typeof buildMSTeamsAttachmentPlaceholder>[0];
28
- type GraphMessageUrlParams = Parameters<typeof buildMSTeamsGraphMessageUrls>[0];
29
- type MSTeamsMediaPayload = ReturnType<typeof buildMSTeamsMediaPayload>;
30
-
31
- const runtimeStub = {
32
- channel: {
33
- text: {
34
- chunkText: (text: string) => (text ? [text] : []),
35
- },
36
- },
37
- } as unknown as PluginRuntime;
38
- const MEDIA_PLACEHOLDER_IMAGE = "<media:image>";
39
- const MEDIA_PLACEHOLDER_DOCUMENT = "<media:document>";
40
- const formatImagePlaceholder = (count: number) =>
41
- count > 1 ? `${MEDIA_PLACEHOLDER_IMAGE} (${count} images)` : MEDIA_PLACEHOLDER_IMAGE;
42
- const formatDocumentPlaceholder = (count: number) =>
43
- count > 1 ? `${MEDIA_PLACEHOLDER_DOCUMENT} (${count} files)` : MEDIA_PLACEHOLDER_DOCUMENT;
44
- const withLabel = <T extends object>(label: string, fields: T): T & { label: string } => ({
45
- label,
46
- ...fields,
47
- });
48
- const buildAttachment = <T extends Record<string, unknown>>(contentType: string, props: T) => ({
49
- contentType,
50
- ...props,
51
- });
52
- const createHtmlAttachment = (content: string) =>
53
- buildAttachment(CONTENT_TYPE_TEXT_HTML, { content });
54
- const buildHtmlImageTag = (src: string) => `<img src="${src}" />`;
55
- const createHtmlImageAttachments = (sources: string[], prefix = "") => [
56
- createHtmlAttachment(`${prefix}${sources.map(buildHtmlImageTag).join("")}`),
57
- ];
58
- const createContentUrlAttachments = (contentType: string, ...contentUrls: string[]) =>
59
- contentUrls.map((contentUrl) => buildAttachment(contentType, { contentUrl }));
60
- const createImageAttachments = (...contentUrls: string[]) =>
61
- createContentUrlAttachments(CONTENT_TYPE_IMAGE_PNG, ...contentUrls);
62
- const createPdfAttachments = (...contentUrls: string[]) =>
63
- createContentUrlAttachments(CONTENT_TYPE_APPLICATION_PDF, ...contentUrls);
64
- const createTeamsFileDownloadInfoAttachments = (
65
- downloadUrl = createTestUrl("dl"),
66
- fileType = "png",
67
- ) => [
68
- buildAttachment(CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO, {
69
- content: { downloadUrl, fileType },
70
- }),
71
- ];
72
- const createMediaEntriesWithType = (contentType: string, ...paths: string[]) =>
73
- paths.map((path) => ({ path, contentType }));
74
- const createImageMediaEntries = (...paths: string[]) =>
75
- createMediaEntriesWithType(CONTENT_TYPE_IMAGE_PNG, ...paths);
76
- const DEFAULT_CHANNEL_TEAM_ID = "team-id";
77
- const DEFAULT_CHANNEL_ID = "chan-id";
78
- const createChannelGraphMessageUrlParams = (params: {
79
- messageId: string;
80
- replyToId?: string;
81
- conversationId?: string;
82
- }) => ({
83
- conversationType: "channel" as const,
84
- ...params,
85
- channelData: {
86
- team: { id: DEFAULT_CHANNEL_TEAM_ID },
87
- channel: { id: DEFAULT_CHANNEL_ID },
88
- },
89
- });
90
- const buildExpectedChannelMessagePath = (params: { messageId: string; replyToId?: string }) =>
91
- params.replyToId
92
- ? `/teams/${DEFAULT_CHANNEL_TEAM_ID}/channels/${DEFAULT_CHANNEL_ID}/messages/${params.replyToId}/replies/${params.messageId}`
93
- : `/teams/${DEFAULT_CHANNEL_TEAM_ID}/channels/${DEFAULT_CHANNEL_ID}/messages/${params.messageId}`;
94
-
95
- const expectMSTeamsMediaPayload = (
96
- payload: MSTeamsMediaPayload,
97
- expected: { firstPath: string; paths: string[]; types: string[] },
98
- ) => {
99
- expect(payload.MediaPath).toBe(expected.firstPath);
100
- expect(payload.MediaUrl).toBe(expected.firstPath);
101
- expect(payload.MediaPaths).toEqual(expected.paths);
102
- expect(payload.MediaUrls).toEqual(expected.paths);
103
- expect(payload.MediaTypes).toEqual(expected.types);
104
- };
105
-
106
- const ATTACHMENT_PLACEHOLDER_CASES = [
107
- withLabel("returns empty string when no attachments", {
108
- attachments: undefined as AttachmentPlaceholderInput,
109
- expected: "",
110
- }),
111
- withLabel("returns empty string when attachments are empty", {
112
- attachments: [],
113
- expected: "",
114
- }),
115
- withLabel("returns image placeholder for one image attachment", {
116
- attachments: createImageAttachments(TEST_URL_IMAGE_PNG),
117
- expected: formatImagePlaceholder(1),
118
- }),
119
- withLabel("returns image placeholder with count for many image attachments", {
120
- attachments: [
121
- ...createImageAttachments(TEST_URL_IMAGE_1_PNG),
122
- { contentType: "image/jpeg", contentUrl: TEST_URL_IMAGE_2_JPG },
123
- ],
124
- expected: formatImagePlaceholder(2),
125
- }),
126
- withLabel("treats Teams file.download.info image attachments as images", {
127
- attachments: createTeamsFileDownloadInfoAttachments(),
128
- expected: formatImagePlaceholder(1),
129
- }),
130
- withLabel("returns document placeholder for non-image attachments", {
131
- attachments: createPdfAttachments(TEST_URL_PDF),
132
- expected: formatDocumentPlaceholder(1),
133
- }),
134
- withLabel("returns document placeholder with count for many non-image attachments", {
135
- attachments: createPdfAttachments(TEST_URL_PDF_1, TEST_URL_PDF_2),
136
- expected: formatDocumentPlaceholder(2),
137
- }),
138
- withLabel("counts one inline image in html attachments", {
139
- attachments: createHtmlImageAttachments([TEST_URL_HTML_A], "<p>hi</p>"),
140
- expected: formatImagePlaceholder(1),
141
- }),
142
- withLabel("counts many inline images in html attachments", {
143
- attachments: createHtmlImageAttachments([TEST_URL_HTML_A, TEST_URL_HTML_B]),
144
- expected: formatImagePlaceholder(2),
145
- }),
146
- ];
147
-
148
- const GRAPH_URL_EXPECTATION_CASES = [
149
- withLabel("builds channel message urls", {
150
- params: createChannelGraphMessageUrlParams({
151
- conversationId: "19:thread@thread.tacv2",
152
- messageId: "123",
153
- }),
154
- expectedPath: buildExpectedChannelMessagePath({ messageId: "123" }),
155
- }),
156
- withLabel("builds channel reply urls when replyToId is present", {
157
- params: createChannelGraphMessageUrlParams({
158
- messageId: "reply-id",
159
- replyToId: "root-id",
160
- }),
161
- expectedPath: buildExpectedChannelMessagePath({
162
- messageId: "reply-id",
163
- replyToId: "root-id",
164
- }),
165
- }),
166
- withLabel("builds chat message urls", {
167
- params: {
168
- conversationType: "groupChat" as const,
169
- conversationId: "19:chat@thread.v2",
170
- messageId: "456",
171
- } satisfies GraphMessageUrlParams,
172
- expectedPath: "/chats/19%3Achat%40thread.v2/messages/456",
173
- }),
174
- ];
175
-
176
- describe("msteams attachment helpers", () => {
177
- beforeEach(() => {
178
- setMSTeamsRuntime(runtimeStub);
179
- });
180
-
181
- describe("buildMSTeamsAttachmentPlaceholder", () => {
182
- it.each(ATTACHMENT_PLACEHOLDER_CASES)("$label", ({ attachments, expected }) => {
183
- expect(buildMSTeamsAttachmentPlaceholder(attachments)).toBe(expected);
184
- });
185
-
186
- it("respects inline image limits when counting placeholder images", () => {
187
- const attachments = [
188
- {
189
- contentType: "text/html",
190
- content: `<img src="data:image/png;base64,${"A".repeat(16)}" />`,
191
- },
192
- ];
193
-
194
- expect(
195
- buildMSTeamsAttachmentPlaceholder(attachments, {
196
- maxInlineBytes: 4,
197
- maxInlineTotalBytes: 4,
198
- }),
199
- ).toBe("<media:document>");
200
- });
201
- });
202
-
203
- describe("buildMSTeamsGraphMessageUrls", () => {
204
- it.each(GRAPH_URL_EXPECTATION_CASES)("$label", ({ params, expectedPath }) => {
205
- const urls = buildMSTeamsGraphMessageUrls(params);
206
- expect(urls[0]).toContain(expectedPath);
207
- });
208
-
209
- it("uses resolved Graph chat ID for personal DMs instead of Bot Framework a: ID", () => {
210
- const urls = buildMSTeamsGraphMessageUrls({
211
- conversationType: "personal",
212
- conversationId: "19:real-graph-chat-id@unq.gbl.spaces",
213
- messageId: "msg-1",
214
- });
215
- expect(urls).toHaveLength(1);
216
- expect(urls[0]).toContain("/chats/19%3Areal-graph-chat-id%40unq.gbl.spaces/messages/msg-1");
217
- });
218
-
219
- it("still builds URLs when a: conversation ID is passed (caller did not resolve)", () => {
220
- const urls = buildMSTeamsGraphMessageUrls({
221
- conversationType: "personal",
222
- conversationId: "a:1dRsHCobZ1AxURzY",
223
- messageId: "msg-1",
224
- });
225
- expect(urls).toHaveLength(1);
226
- expect(urls[0]).toContain("/chats/a%3A1dRsHCobZ1AxURzY/messages/msg-1");
227
- });
228
- });
229
-
230
- describe("buildMSTeamsMediaPayload", () => {
231
- it("returns single and multi-file fields", () => {
232
- const payload = buildMSTeamsMediaPayload(createImageMediaEntries("/tmp/a.png", "/tmp/b.png"));
233
- expectMSTeamsMediaPayload(payload, {
234
- firstPath: "/tmp/a.png",
235
- paths: ["/tmp/a.png", "/tmp/b.png"],
236
- types: [CONTENT_TYPE_IMAGE_PNG, CONTENT_TYPE_IMAGE_PNG],
237
- });
238
- });
239
- });
240
-
241
- it("retains the expected sharepoint host fixture", () => {
242
- expect(SHAREPOINT_HOST).toBe("contoso.sharepoint.com");
243
- expect(TEST_URL_IMAGE).toContain(TEST_HOST);
244
- });
245
- });
@@ -1,17 +0,0 @@
1
- export async function readRemoteMediaResponse(
2
- res: Response,
3
- params: { maxBytes?: number; filePathHint?: string },
4
- ) {
5
- if (!res.ok) {
6
- throw new Error(`HTTP ${res.status}`);
7
- }
8
- const buffer = Buffer.from(await res.arrayBuffer());
9
- if (typeof params.maxBytes === "number" && buffer.byteLength > params.maxBytes) {
10
- throw new Error(`payload exceeds maxBytes ${params.maxBytes}`);
11
- }
12
- return {
13
- buffer,
14
- contentType: res.headers.get("content-type") ?? undefined,
15
- fileName: params.filePathHint,
16
- };
17
- }