@openclaw/msteams 2026.5.2 → 2026.5.3-beta.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 (197) hide show
  1. package/dist/api.js +3 -0
  2. package/dist/channel-D7hdreTh.js +984 -0
  3. package/dist/channel-config-api.js +2 -0
  4. package/dist/channel-plugin-api.js +2 -0
  5. package/dist/channel.runtime-BC1ruIfN.js +573 -0
  6. package/dist/config-schema-B8QezH6t.js +15 -0
  7. package/dist/contract-api.js +2 -0
  8. package/dist/graph-users-9uQJepqr.js +1354 -0
  9. package/dist/index.js +22 -0
  10. package/dist/oauth-BWJyilR1.js +114 -0
  11. package/dist/oauth.token-xxpoLWy5.js +115 -0
  12. package/dist/policy-DTnU2GR7.js +142 -0
  13. package/dist/probe-D_H8yFps.js +2194 -0
  14. package/dist/resolve-allowlist-D41JSziq.js +219 -0
  15. package/dist/runtime-api-DV1iVMn1.js +28 -0
  16. package/dist/runtime-api.js +2 -0
  17. package/dist/secret-contract-BuoEXmPS.js +35 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/setup-entry.js +15 -0
  20. package/dist/setup-plugin-api.js +64 -0
  21. package/dist/setup-surface-BLkFQYIQ.js +313 -0
  22. package/dist/src-CFp1QpFd.js +4064 -0
  23. package/dist/test-api.js +2 -0
  24. package/package.json +14 -6
  25. package/api.ts +0 -3
  26. package/channel-config-api.ts +0 -1
  27. package/channel-plugin-api.ts +0 -2
  28. package/config-api.ts +0 -4
  29. package/contract-api.ts +0 -4
  30. package/index.ts +0 -20
  31. package/runtime-api.ts +0 -73
  32. package/secret-contract-api.ts +0 -5
  33. package/setup-entry.ts +0 -13
  34. package/setup-plugin-api.ts +0 -3
  35. package/src/ai-entity.ts +0 -7
  36. package/src/approval-auth.ts +0 -44
  37. package/src/attachments/bot-framework.test.ts +0 -461
  38. package/src/attachments/bot-framework.ts +0 -362
  39. package/src/attachments/download.ts +0 -311
  40. package/src/attachments/graph.test.ts +0 -416
  41. package/src/attachments/graph.ts +0 -484
  42. package/src/attachments/html.ts +0 -122
  43. package/src/attachments/payload.ts +0 -14
  44. package/src/attachments/remote-media.test.ts +0 -137
  45. package/src/attachments/remote-media.ts +0 -112
  46. package/src/attachments/shared.test.ts +0 -530
  47. package/src/attachments/shared.ts +0 -626
  48. package/src/attachments/types.ts +0 -47
  49. package/src/attachments.graph.test.ts +0 -342
  50. package/src/attachments.helpers.test.ts +0 -246
  51. package/src/attachments.test-helpers.ts +0 -17
  52. package/src/attachments.test.ts +0 -687
  53. package/src/attachments.ts +0 -18
  54. package/src/block-streaming-config.test.ts +0 -61
  55. package/src/channel-api.ts +0 -1
  56. package/src/channel.actions.test.ts +0 -742
  57. package/src/channel.directory.test.ts +0 -200
  58. package/src/channel.runtime.ts +0 -56
  59. package/src/channel.setup.ts +0 -77
  60. package/src/channel.test.ts +0 -128
  61. package/src/channel.ts +0 -1136
  62. package/src/config-schema.ts +0 -6
  63. package/src/config-ui-hints.ts +0 -12
  64. package/src/conversation-store-fs.test.ts +0 -74
  65. package/src/conversation-store-fs.ts +0 -149
  66. package/src/conversation-store-helpers.test.ts +0 -202
  67. package/src/conversation-store-helpers.ts +0 -105
  68. package/src/conversation-store-memory.ts +0 -51
  69. package/src/conversation-store.shared.test.ts +0 -225
  70. package/src/conversation-store.ts +0 -71
  71. package/src/directory-live.test.ts +0 -156
  72. package/src/directory-live.ts +0 -111
  73. package/src/doctor.ts +0 -27
  74. package/src/errors.test.ts +0 -133
  75. package/src/errors.ts +0 -246
  76. package/src/feedback-reflection-prompt.ts +0 -117
  77. package/src/feedback-reflection-store.ts +0 -114
  78. package/src/feedback-reflection.test.ts +0 -237
  79. package/src/feedback-reflection.ts +0 -283
  80. package/src/file-consent-helpers.test.ts +0 -326
  81. package/src/file-consent-helpers.ts +0 -126
  82. package/src/file-consent-invoke.ts +0 -150
  83. package/src/file-consent.test.ts +0 -363
  84. package/src/file-consent.ts +0 -287
  85. package/src/graph-chat.ts +0 -55
  86. package/src/graph-group-management.test.ts +0 -318
  87. package/src/graph-group-management.ts +0 -168
  88. package/src/graph-members.test.ts +0 -89
  89. package/src/graph-members.ts +0 -48
  90. package/src/graph-messages.actions.test.ts +0 -243
  91. package/src/graph-messages.read.test.ts +0 -391
  92. package/src/graph-messages.search.test.ts +0 -213
  93. package/src/graph-messages.test-helpers.ts +0 -50
  94. package/src/graph-messages.ts +0 -534
  95. package/src/graph-teams.test.ts +0 -215
  96. package/src/graph-teams.ts +0 -114
  97. package/src/graph-thread.test.ts +0 -246
  98. package/src/graph-thread.ts +0 -146
  99. package/src/graph-upload.test.ts +0 -258
  100. package/src/graph-upload.ts +0 -531
  101. package/src/graph-users.ts +0 -29
  102. package/src/graph.test.ts +0 -516
  103. package/src/graph.ts +0 -293
  104. package/src/inbound.test.ts +0 -221
  105. package/src/inbound.ts +0 -148
  106. package/src/index.ts +0 -4
  107. package/src/media-helpers.test.ts +0 -202
  108. package/src/media-helpers.ts +0 -105
  109. package/src/mentions.test.ts +0 -244
  110. package/src/mentions.ts +0 -114
  111. package/src/messenger.test.ts +0 -865
  112. package/src/messenger.ts +0 -605
  113. package/src/monitor-handler/access.ts +0 -125
  114. package/src/monitor-handler/inbound-media.test.ts +0 -289
  115. package/src/monitor-handler/inbound-media.ts +0 -180
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  117. package/src/monitor-handler/message-handler.authz.test.ts +0 -669
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  119. package/src/monitor-handler/message-handler.test-support.ts +0 -100
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -223
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -77
  122. package/src/monitor-handler/message-handler.ts +0 -1000
  123. package/src/monitor-handler/reaction-handler.test.ts +0 -267
  124. package/src/monitor-handler/reaction-handler.ts +0 -210
  125. package/src/monitor-handler/thread-session.ts +0 -17
  126. package/src/monitor-handler.adaptive-card.test.ts +0 -162
  127. package/src/monitor-handler.feedback-authz.test.ts +0 -314
  128. package/src/monitor-handler.file-consent.test.ts +0 -423
  129. package/src/monitor-handler.sso.test.ts +0 -563
  130. package/src/monitor-handler.test-helpers.ts +0 -180
  131. package/src/monitor-handler.ts +0 -534
  132. package/src/monitor-handler.types.ts +0 -27
  133. package/src/monitor-types.ts +0 -6
  134. package/src/monitor.lifecycle.test.ts +0 -278
  135. package/src/monitor.test.ts +0 -119
  136. package/src/monitor.ts +0 -442
  137. package/src/oauth.flow.ts +0 -77
  138. package/src/oauth.shared.ts +0 -37
  139. package/src/oauth.test.ts +0 -305
  140. package/src/oauth.token.ts +0 -158
  141. package/src/oauth.ts +0 -130
  142. package/src/outbound.test.ts +0 -130
  143. package/src/outbound.ts +0 -71
  144. package/src/pending-uploads-fs.test.ts +0 -246
  145. package/src/pending-uploads-fs.ts +0 -235
  146. package/src/pending-uploads.test.ts +0 -173
  147. package/src/pending-uploads.ts +0 -121
  148. package/src/policy.test.ts +0 -240
  149. package/src/policy.ts +0 -262
  150. package/src/polls-store-memory.ts +0 -32
  151. package/src/polls.test.ts +0 -160
  152. package/src/polls.ts +0 -323
  153. package/src/presentation.ts +0 -68
  154. package/src/probe.test.ts +0 -77
  155. package/src/probe.ts +0 -132
  156. package/src/reply-dispatcher.test.ts +0 -437
  157. package/src/reply-dispatcher.ts +0 -346
  158. package/src/reply-stream-controller.test.ts +0 -235
  159. package/src/reply-stream-controller.ts +0 -147
  160. package/src/resolve-allowlist.test.ts +0 -250
  161. package/src/resolve-allowlist.ts +0 -309
  162. package/src/revoked-context.ts +0 -17
  163. package/src/runtime.ts +0 -9
  164. package/src/sdk-types.ts +0 -59
  165. package/src/sdk.test.ts +0 -666
  166. package/src/sdk.ts +0 -884
  167. package/src/secret-contract.ts +0 -49
  168. package/src/secret-input.ts +0 -7
  169. package/src/send-context.ts +0 -231
  170. package/src/send.test.ts +0 -493
  171. package/src/send.ts +0 -637
  172. package/src/sent-message-cache.test.ts +0 -15
  173. package/src/sent-message-cache.ts +0 -56
  174. package/src/session-route.ts +0 -40
  175. package/src/setup-core.ts +0 -160
  176. package/src/setup-surface.test.ts +0 -202
  177. package/src/setup-surface.ts +0 -320
  178. package/src/sso-token-store.test.ts +0 -72
  179. package/src/sso-token-store.ts +0 -166
  180. package/src/sso.ts +0 -300
  181. package/src/storage.ts +0 -25
  182. package/src/store-fs.ts +0 -44
  183. package/src/streaming-message.test.ts +0 -262
  184. package/src/streaming-message.ts +0 -297
  185. package/src/test-runtime.ts +0 -16
  186. package/src/thread-parent-context.test.ts +0 -224
  187. package/src/thread-parent-context.ts +0 -159
  188. package/src/token-response.ts +0 -11
  189. package/src/token.test.ts +0 -259
  190. package/src/token.ts +0 -195
  191. package/src/user-agent.test.ts +0 -86
  192. package/src/user-agent.ts +0 -53
  193. package/src/webhook-timeouts.ts +0 -27
  194. package/src/welcome-card.test.ts +0 -81
  195. package/src/welcome-card.ts +0 -57
  196. package/test-api.ts +0 -1
  197. package/tsconfig.json +0 -16
@@ -1,342 +0,0 @@
1
- import { mockPinnedHostnameResolution } from "openclaw/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 { 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(async () => ({
22
- id: "saved.png",
23
- path: "/tmp/saved.png",
24
- size: Buffer.byteLength(PNG_BUFFER),
25
- contentType: CONTENT_TYPE_IMAGE_PNG,
26
- }));
27
- const fetchRemoteMediaMock = vi.fn(
28
- async (params: {
29
- url: string;
30
- maxBytes?: number;
31
- filePathHint?: string;
32
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
33
- }) => {
34
- const fetchFn = params.fetchImpl ?? fetch;
35
- const res = await fetchFn(params.url, { redirect: "manual" });
36
- return readRemoteMediaResponse(res, params);
37
- },
38
- );
39
-
40
- const runtimeStub = {
41
- media: {
42
- detectMime: detectMimeMock,
43
- },
44
- channel: {
45
- media: {
46
- fetchRemoteMedia: fetchRemoteMediaMock,
47
- saveMediaBuffer: saveMediaBufferMock,
48
- },
49
- },
50
- } as unknown as PluginRuntime;
51
-
52
- type DownloadGraphMediaParams = Parameters<typeof downloadMSTeamsGraphMedia>[0];
53
- type DownloadGraphMediaOverrides = Partial<
54
- Omit<DownloadGraphMediaParams, "messageUrl" | "tokenProvider">
55
- >;
56
- type FetchFn = typeof fetch;
57
- type LabeledCase = { label: string };
58
- type GraphFetchMockOptions = {
59
- hostedContents?: unknown[];
60
- attachments?: unknown[];
61
- messageAttachments?: unknown[];
62
- onShareRequest?: (url: string) => Response | Promise<Response>;
63
- onUnhandled?: (url: string) => Response | Promise<Response> | undefined;
64
- };
65
- type GraphMediaDownloadResult = {
66
- fetchMock: ReturnType<typeof createGraphFetchMock>;
67
- media: Awaited<ReturnType<typeof downloadMSTeamsGraphMedia>>;
68
- };
69
- type GraphMediaSuccessCase = LabeledCase & {
70
- buildOptions: () => GraphFetchMockOptions;
71
- expectedLength: number;
72
- assert?: (params: GraphMediaDownloadResult) => void;
73
- };
74
-
75
- const withLabel = <T extends object>(label: string, fields: T): T & LabeledCase => ({
76
- label,
77
- ...fields,
78
- });
79
- const createTokenProvider = (
80
- tokenOrResolver: string | ((scope: string) => string | Promise<string>) = "token",
81
- ) => ({
82
- getAccessToken: vi.fn(async (scope: string) =>
83
- typeof tokenOrResolver === "function" ? await tokenOrResolver(scope) : tokenOrResolver,
84
- ),
85
- });
86
- const createBufferResponse = (payload: Buffer | string, contentType: string, status = 200) => {
87
- const raw = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
88
- return new Response(new Uint8Array(raw), {
89
- status,
90
- headers: { "content-type": contentType },
91
- });
92
- };
93
- const createPdfResponse = (payload: Buffer | string = Buffer.from("pdf")) =>
94
- createBufferResponse(payload, CONTENT_TYPE_APPLICATION_PDF);
95
- const createJsonResponse = (payload: unknown, status = 200) =>
96
- new Response(JSON.stringify(payload), { status });
97
- const createGraphCollectionResponse = (value: unknown[]) => createJsonResponse({ value });
98
- const createNotFoundResponse = () => new Response("not found", { status: 404 });
99
- const createRedirectResponse = (location: string, status = 302) =>
100
- new Response(null, { status, headers: { location } });
101
- const asFetchFn = (fetchFn: unknown): FetchFn => fetchFn as FetchFn;
102
- const expectAttachmentMediaLength = (
103
- media: Awaited<ReturnType<typeof downloadMSTeamsGraphMedia>>["media"],
104
- expectedLength: number,
105
- ) => {
106
- expect(media).toHaveLength(expectedLength);
107
- };
108
- const expectMediaBufferSaved = () => {
109
- expect(saveMediaBufferMock).toHaveBeenCalled();
110
- };
111
-
112
- const createHostedContentsWithType = (contentType: string, ...ids: string[]) =>
113
- ids.map((id) => ({ id, contentType, contentBytes: PNG_BUFFER.toString("base64") }));
114
- const createHostedImageContents = (...ids: string[]) =>
115
- createHostedContentsWithType(CONTENT_TYPE_IMAGE_PNG, ...ids);
116
- const createReferenceAttachment = (shareUrl = DEFAULT_SHARE_REFERENCE_URL) => ({
117
- id: "ref-1",
118
- contentType: "reference",
119
- contentUrl: shareUrl,
120
- name: "report.pdf",
121
- });
122
- const buildShareReferenceGraphFetchOptions = (params: {
123
- referenceAttachment: ReturnType<typeof createReferenceAttachment>;
124
- onShareRequest?: GraphFetchMockOptions["onShareRequest"];
125
- onUnhandled?: GraphFetchMockOptions["onUnhandled"];
126
- }) => ({
127
- attachments: [params.referenceAttachment],
128
- messageAttachments: [params.referenceAttachment],
129
- ...(params.onShareRequest ? { onShareRequest: params.onShareRequest } : {}),
130
- ...(params.onUnhandled ? { onUnhandled: params.onUnhandled } : {}),
131
- });
132
- const buildDefaultShareReferenceGraphFetchOptions = (
133
- params: Omit<Parameters<typeof buildShareReferenceGraphFetchOptions>[0], "referenceAttachment">,
134
- ) =>
135
- buildShareReferenceGraphFetchOptions({
136
- referenceAttachment: createReferenceAttachment(),
137
- ...params,
138
- });
139
- type GraphEndpointResponseHandler = {
140
- suffix: string;
141
- buildResponse: () => Response;
142
- };
143
- const createGraphEndpointResponseHandlers = (params: {
144
- hostedContents: unknown[];
145
- attachments: unknown[];
146
- messageAttachments: unknown[];
147
- }): GraphEndpointResponseHandler[] => [
148
- {
149
- suffix: "/hostedContents",
150
- buildResponse: () => createGraphCollectionResponse(params.hostedContents),
151
- },
152
- {
153
- suffix: "/attachments",
154
- buildResponse: () => createGraphCollectionResponse(params.attachments),
155
- },
156
- {
157
- suffix: "/messages/123",
158
- buildResponse: () => createJsonResponse({ attachments: params.messageAttachments }),
159
- },
160
- ];
161
- const resolveGraphEndpointResponse = (
162
- url: string,
163
- handlers: GraphEndpointResponseHandler[],
164
- ): Response | undefined => {
165
- const handler = handlers.find((entry) => url.endsWith(entry.suffix));
166
- return handler ? handler.buildResponse() : undefined;
167
- };
168
-
169
- const createGraphFetchMock = (options: GraphFetchMockOptions = {}) => {
170
- const hostedContents = options.hostedContents ?? [];
171
- const attachments = options.attachments ?? [];
172
- const messageAttachments = options.messageAttachments ?? [];
173
- const endpointHandlers = createGraphEndpointResponseHandlers({
174
- hostedContents,
175
- attachments,
176
- messageAttachments,
177
- });
178
- return vi.fn(async (url: string) => {
179
- const endpointResponse = resolveGraphEndpointResponse(url, endpointHandlers);
180
- if (endpointResponse) {
181
- return endpointResponse;
182
- }
183
- if (url.startsWith(GRAPH_SHARES_URL_PREFIX) && options.onShareRequest) {
184
- return options.onShareRequest(url);
185
- }
186
- const unhandled = options.onUnhandled ? await options.onUnhandled(url) : undefined;
187
- return unhandled ?? createNotFoundResponse();
188
- });
189
- };
190
- const downloadGraphMediaWithMockOptions = async (
191
- options: GraphFetchMockOptions = {},
192
- overrides: DownloadGraphMediaOverrides = {},
193
- ): Promise<GraphMediaDownloadResult> => {
194
- const fetchMock = createGraphFetchMock(options);
195
- const media = await downloadMSTeamsGraphMedia({
196
- messageUrl: DEFAULT_MESSAGE_URL,
197
- tokenProvider: createTokenProvider(),
198
- maxBytes: DEFAULT_MAX_BYTES,
199
- fetchFn: asFetchFn(fetchMock),
200
- ...overrides,
201
- });
202
- return { fetchMock, media };
203
- };
204
- const runGraphMediaSuccessCase = async ({
205
- buildOptions,
206
- expectedLength,
207
- assert,
208
- }: GraphMediaSuccessCase) => {
209
- const { fetchMock, media } = await downloadGraphMediaWithMockOptions(buildOptions());
210
- expectAttachmentMediaLength(media.media, expectedLength);
211
- assert?.({ fetchMock, media });
212
- };
213
-
214
- const GRAPH_MEDIA_SUCCESS_CASES: GraphMediaSuccessCase[] = [
215
- withLabel("downloads hostedContents images", {
216
- buildOptions: () => ({ hostedContents: createHostedImageContents("1") }),
217
- expectedLength: 1,
218
- assert: ({ fetchMock }) => {
219
- expect(fetchMock).toHaveBeenCalled();
220
- expectMediaBufferSaved();
221
- },
222
- }),
223
- withLabel("merges SharePoint reference attachments with hosted content", {
224
- buildOptions: () => {
225
- return {
226
- hostedContents: createHostedImageContents("hosted-1"),
227
- ...buildDefaultShareReferenceGraphFetchOptions({
228
- onShareRequest: () => createPdfResponse(),
229
- }),
230
- };
231
- },
232
- expectedLength: 2,
233
- }),
234
- ];
235
-
236
- describe("msteams graph attachments", () => {
237
- let ssrfMock: { mockRestore: () => void } | undefined;
238
-
239
- beforeEach(() => {
240
- ssrfMock?.mockRestore();
241
- ssrfMock = mockPinnedHostnameResolution();
242
- detectMimeMock.mockClear();
243
- fetchRemoteMediaMock.mockClear();
244
- saveMediaBufferMock.mockClear();
245
- setMSTeamsRuntime(runtimeStub);
246
- });
247
-
248
- it.each<GraphMediaSuccessCase>(GRAPH_MEDIA_SUCCESS_CASES)("$label", runGraphMediaSuccessCase);
249
-
250
- it("does not forward Authorization for SharePoint redirects outside auth allowlist", async () => {
251
- const tokenProvider = createTokenProvider("top-secret-token");
252
- const escapedUrl = "https://example.com/collect";
253
- const seen: Array<{ url: string; auth: string }> = [];
254
- const referenceAttachment = createReferenceAttachment();
255
- const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
256
- const url = resolveRequestUrl(input);
257
- const auth = new Headers(init?.headers).get("Authorization") ?? "";
258
- seen.push({ url, auth });
259
-
260
- if (url === DEFAULT_MESSAGE_URL) {
261
- return createJsonResponse({ attachments: [referenceAttachment] });
262
- }
263
- if (url === `${DEFAULT_MESSAGE_URL}/hostedContents`) {
264
- return createGraphCollectionResponse([]);
265
- }
266
- if (url === `${DEFAULT_MESSAGE_URL}/attachments`) {
267
- return createGraphCollectionResponse([referenceAttachment]);
268
- }
269
- if (url.startsWith(GRAPH_SHARES_URL_PREFIX)) {
270
- return createRedirectResponse(escapedUrl);
271
- }
272
- if (url === escapedUrl) {
273
- return createPdfResponse();
274
- }
275
- return createNotFoundResponse();
276
- });
277
-
278
- const media = await downloadMSTeamsGraphMedia({
279
- messageUrl: DEFAULT_MESSAGE_URL,
280
- tokenProvider,
281
- maxBytes: DEFAULT_MAX_BYTES,
282
- allowHosts: [...DEFAULT_SHAREPOINT_ALLOW_HOSTS, "example.com"],
283
- authAllowHosts: DEFAULT_SHAREPOINT_ALLOW_HOSTS,
284
- fetchFn: asFetchFn(fetchMock),
285
- });
286
-
287
- expectAttachmentMediaLength(media.media, 1);
288
- const redirected = seen.find((entry) => entry.url === escapedUrl);
289
- expect(redirected).toBeDefined();
290
- expect(redirected?.auth).toBe("");
291
- });
292
-
293
- it("blocks SharePoint redirects to hosts outside allowHosts", async () => {
294
- const escapedUrl = "https://evil.example/internal.pdf";
295
- const { fetchMock, media } = await downloadGraphMediaWithMockOptions(
296
- {
297
- ...buildDefaultShareReferenceGraphFetchOptions({
298
- onShareRequest: () => createRedirectResponse(escapedUrl),
299
- onUnhandled: (url) => {
300
- if (url === escapedUrl) {
301
- return createPdfResponse("should-not-be-fetched");
302
- }
303
- return undefined;
304
- },
305
- }),
306
- },
307
- {
308
- allowHosts: DEFAULT_SHAREPOINT_ALLOW_HOSTS,
309
- },
310
- );
311
-
312
- expectAttachmentMediaLength(media.media, 0);
313
- const calledUrls = fetchMock.mock.calls.map((call) => call[0]);
314
- expect(calledUrls.some((url) => url.startsWith(GRAPH_SHARES_URL_PREFIX))).toBe(true);
315
- expect(calledUrls).not.toContain(escapedUrl);
316
- });
317
-
318
- it("skips inline hosted content when estimated decoded bytes exceed maxBytes", async () => {
319
- const oversizedBase64 = "A".repeat(16);
320
- const bufferFromSpy = vi.spyOn(Buffer, "from");
321
-
322
- try {
323
- const { media } = await downloadGraphMediaWithMockOptions(
324
- {
325
- hostedContents: [
326
- {
327
- id: "hosted-oversized",
328
- contentType: CONTENT_TYPE_IMAGE_PNG,
329
- contentBytes: oversizedBase64,
330
- },
331
- ],
332
- },
333
- { maxBytes: 4 },
334
- );
335
-
336
- expect(media.media).toEqual([]);
337
- expect(bufferFromSpy).not.toHaveBeenCalledWith(oversizedBase64, "base64");
338
- } finally {
339
- bufferFromSpy.mockRestore();
340
- }
341
- });
342
- });
@@ -1,246 +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 _GRAPH_HOST = "graph.microsoft.com";
11
- const SHAREPOINT_HOST = "contoso.sharepoint.com";
12
- const TEST_HOST = "x";
13
- const createUrlForHost = (host: string, pathSegment: string) => `https://${host}/${pathSegment}`;
14
- const createTestUrl = (pathSegment: string) => createUrlForHost(TEST_HOST, pathSegment);
15
- const TEST_URL_IMAGE = createTestUrl("img");
16
- const TEST_URL_IMAGE_PNG = createTestUrl("img.png");
17
- const TEST_URL_IMAGE_1_PNG = createTestUrl("1.png");
18
- const TEST_URL_IMAGE_2_JPG = createTestUrl("2.jpg");
19
- const TEST_URL_PDF = createTestUrl("x.pdf");
20
- const TEST_URL_PDF_1 = createTestUrl("1.pdf");
21
- const TEST_URL_PDF_2 = createTestUrl("2.pdf");
22
- const TEST_URL_HTML_A = createTestUrl("a.png");
23
- const TEST_URL_HTML_B = createTestUrl("b.png");
24
- const CONTENT_TYPE_IMAGE_PNG = "image/png";
25
- const CONTENT_TYPE_APPLICATION_PDF = "application/pdf";
26
- const CONTENT_TYPE_TEXT_HTML = "text/html";
27
- const CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info";
28
- type AttachmentPlaceholderInput = Parameters<typeof buildMSTeamsAttachmentPlaceholder>[0];
29
- type GraphMessageUrlParams = Parameters<typeof buildMSTeamsGraphMessageUrls>[0];
30
- type MSTeamsMediaPayload = ReturnType<typeof buildMSTeamsMediaPayload>;
31
-
32
- const runtimeStub = {
33
- channel: {
34
- text: {
35
- chunkText: (text: string) => (text ? [text] : []),
36
- },
37
- },
38
- } as unknown as PluginRuntime;
39
- const MEDIA_PLACEHOLDER_IMAGE = "<media:image>";
40
- const MEDIA_PLACEHOLDER_DOCUMENT = "<media:document>";
41
- const formatImagePlaceholder = (count: number) =>
42
- count > 1 ? `${MEDIA_PLACEHOLDER_IMAGE} (${count} images)` : MEDIA_PLACEHOLDER_IMAGE;
43
- const formatDocumentPlaceholder = (count: number) =>
44
- count > 1 ? `${MEDIA_PLACEHOLDER_DOCUMENT} (${count} files)` : MEDIA_PLACEHOLDER_DOCUMENT;
45
- const withLabel = <T extends object>(label: string, fields: T): T & { label: string } => ({
46
- label,
47
- ...fields,
48
- });
49
- const buildAttachment = <T extends Record<string, unknown>>(contentType: string, props: T) => ({
50
- contentType,
51
- ...props,
52
- });
53
- const createHtmlAttachment = (content: string) =>
54
- buildAttachment(CONTENT_TYPE_TEXT_HTML, { content });
55
- const buildHtmlImageTag = (src: string) => `<img src="${src}" />`;
56
- const createHtmlImageAttachments = (sources: string[], prefix = "") => [
57
- createHtmlAttachment(`${prefix}${sources.map(buildHtmlImageTag).join("")}`),
58
- ];
59
- const createContentUrlAttachments = (contentType: string, ...contentUrls: string[]) =>
60
- contentUrls.map((contentUrl) => buildAttachment(contentType, { contentUrl }));
61
- const createImageAttachments = (...contentUrls: string[]) =>
62
- createContentUrlAttachments(CONTENT_TYPE_IMAGE_PNG, ...contentUrls);
63
- const createPdfAttachments = (...contentUrls: string[]) =>
64
- createContentUrlAttachments(CONTENT_TYPE_APPLICATION_PDF, ...contentUrls);
65
- const createTeamsFileDownloadInfoAttachments = (
66
- downloadUrl = createTestUrl("dl"),
67
- fileType = "png",
68
- ) => [
69
- buildAttachment(CONTENT_TYPE_TEAMS_FILE_DOWNLOAD_INFO, {
70
- content: { downloadUrl, fileType },
71
- }),
72
- ];
73
- const createMediaEntriesWithType = (contentType: string, ...paths: string[]) =>
74
- paths.map((path) => ({ path, contentType }));
75
- const createImageMediaEntries = (...paths: string[]) =>
76
- createMediaEntriesWithType(CONTENT_TYPE_IMAGE_PNG, ...paths);
77
- const DEFAULT_CHANNEL_TEAM_ID = "team-id";
78
- const DEFAULT_CHANNEL_ID = "chan-id";
79
- const createChannelGraphMessageUrlParams = (params: {
80
- messageId: string;
81
- replyToId?: string;
82
- conversationId?: string;
83
- }) => ({
84
- conversationType: "channel" as const,
85
- ...params,
86
- channelData: {
87
- team: { id: DEFAULT_CHANNEL_TEAM_ID },
88
- channel: { id: DEFAULT_CHANNEL_ID },
89
- },
90
- });
91
- const buildExpectedChannelMessagePath = (params: { messageId: string; replyToId?: string }) =>
92
- params.replyToId
93
- ? `/teams/${DEFAULT_CHANNEL_TEAM_ID}/channels/${DEFAULT_CHANNEL_ID}/messages/${params.replyToId}/replies/${params.messageId}`
94
- : `/teams/${DEFAULT_CHANNEL_TEAM_ID}/channels/${DEFAULT_CHANNEL_ID}/messages/${params.messageId}`;
95
-
96
- const expectMSTeamsMediaPayload = (
97
- payload: MSTeamsMediaPayload,
98
- expected: { firstPath: string; paths: string[]; types: string[] },
99
- ) => {
100
- expect(payload.MediaPath).toBe(expected.firstPath);
101
- expect(payload.MediaUrl).toBe(expected.firstPath);
102
- expect(payload.MediaPaths).toEqual(expected.paths);
103
- expect(payload.MediaUrls).toEqual(expected.paths);
104
- expect(payload.MediaTypes).toEqual(expected.types);
105
- };
106
-
107
- const ATTACHMENT_PLACEHOLDER_CASES = [
108
- withLabel("returns empty string when no attachments", {
109
- attachments: undefined as AttachmentPlaceholderInput,
110
- expected: "",
111
- }),
112
- withLabel("returns empty string when attachments are empty", {
113
- attachments: [],
114
- expected: "",
115
- }),
116
- withLabel("returns image placeholder for one image attachment", {
117
- attachments: createImageAttachments(TEST_URL_IMAGE_PNG),
118
- expected: formatImagePlaceholder(1),
119
- }),
120
- withLabel("returns image placeholder with count for many image attachments", {
121
- attachments: [
122
- ...createImageAttachments(TEST_URL_IMAGE_1_PNG),
123
- { contentType: "image/jpeg", contentUrl: TEST_URL_IMAGE_2_JPG },
124
- ],
125
- expected: formatImagePlaceholder(2),
126
- }),
127
- withLabel("treats Teams file.download.info image attachments as images", {
128
- attachments: createTeamsFileDownloadInfoAttachments(),
129
- expected: formatImagePlaceholder(1),
130
- }),
131
- withLabel("returns document placeholder for non-image attachments", {
132
- attachments: createPdfAttachments(TEST_URL_PDF),
133
- expected: formatDocumentPlaceholder(1),
134
- }),
135
- withLabel("returns document placeholder with count for many non-image attachments", {
136
- attachments: createPdfAttachments(TEST_URL_PDF_1, TEST_URL_PDF_2),
137
- expected: formatDocumentPlaceholder(2),
138
- }),
139
- withLabel("counts one inline image in html attachments", {
140
- attachments: createHtmlImageAttachments([TEST_URL_HTML_A], "<p>hi</p>"),
141
- expected: formatImagePlaceholder(1),
142
- }),
143
- withLabel("counts many inline images in html attachments", {
144
- attachments: createHtmlImageAttachments([TEST_URL_HTML_A, TEST_URL_HTML_B]),
145
- expected: formatImagePlaceholder(2),
146
- }),
147
- ];
148
-
149
- const GRAPH_URL_EXPECTATION_CASES = [
150
- withLabel("builds channel message urls", {
151
- params: createChannelGraphMessageUrlParams({
152
- conversationId: "19:thread@thread.tacv2",
153
- messageId: "123",
154
- }),
155
- expectedPath: buildExpectedChannelMessagePath({ messageId: "123" }),
156
- }),
157
- withLabel("builds channel reply urls when replyToId is present", {
158
- params: createChannelGraphMessageUrlParams({
159
- messageId: "reply-id",
160
- replyToId: "root-id",
161
- }),
162
- expectedPath: buildExpectedChannelMessagePath({
163
- messageId: "reply-id",
164
- replyToId: "root-id",
165
- }),
166
- }),
167
- withLabel("builds chat message urls", {
168
- params: {
169
- conversationType: "groupChat" as const,
170
- conversationId: "19:chat@thread.v2",
171
- messageId: "456",
172
- } satisfies GraphMessageUrlParams,
173
- expectedPath: "/chats/19%3Achat%40thread.v2/messages/456",
174
- }),
175
- ];
176
-
177
- describe("msteams attachment helpers", () => {
178
- beforeEach(() => {
179
- setMSTeamsRuntime(runtimeStub);
180
- });
181
-
182
- describe("buildMSTeamsAttachmentPlaceholder", () => {
183
- it.each(ATTACHMENT_PLACEHOLDER_CASES)("$label", ({ attachments, expected }) => {
184
- expect(buildMSTeamsAttachmentPlaceholder(attachments)).toBe(expected);
185
- });
186
-
187
- it("respects inline image limits when counting placeholder images", () => {
188
- const attachments = [
189
- {
190
- contentType: "text/html",
191
- content: `<img src="data:image/png;base64,${"A".repeat(16)}" />`,
192
- },
193
- ];
194
-
195
- expect(
196
- buildMSTeamsAttachmentPlaceholder(attachments, {
197
- maxInlineBytes: 4,
198
- maxInlineTotalBytes: 4,
199
- }),
200
- ).toBe("<media:document>");
201
- });
202
- });
203
-
204
- describe("buildMSTeamsGraphMessageUrls", () => {
205
- it.each(GRAPH_URL_EXPECTATION_CASES)("$label", ({ params, expectedPath }) => {
206
- const urls = buildMSTeamsGraphMessageUrls(params);
207
- expect(urls[0]).toContain(expectedPath);
208
- });
209
-
210
- it("uses resolved Graph chat ID for personal DMs instead of Bot Framework a: ID", () => {
211
- const urls = buildMSTeamsGraphMessageUrls({
212
- conversationType: "personal",
213
- conversationId: "19:real-graph-chat-id@unq.gbl.spaces",
214
- messageId: "msg-1",
215
- });
216
- expect(urls).toHaveLength(1);
217
- expect(urls[0]).toContain("/chats/19%3Areal-graph-chat-id%40unq.gbl.spaces/messages/msg-1");
218
- });
219
-
220
- it("still builds URLs when a: conversation ID is passed (caller did not resolve)", () => {
221
- const urls = buildMSTeamsGraphMessageUrls({
222
- conversationType: "personal",
223
- conversationId: "a:1dRsHCobZ1AxURzY",
224
- messageId: "msg-1",
225
- });
226
- expect(urls).toHaveLength(1);
227
- expect(urls[0]).toContain("/chats/a%3A1dRsHCobZ1AxURzY/messages/msg-1");
228
- });
229
- });
230
-
231
- describe("buildMSTeamsMediaPayload", () => {
232
- it("returns single and multi-file fields", () => {
233
- const payload = buildMSTeamsMediaPayload(createImageMediaEntries("/tmp/a.png", "/tmp/b.png"));
234
- expectMSTeamsMediaPayload(payload, {
235
- firstPath: "/tmp/a.png",
236
- paths: ["/tmp/a.png", "/tmp/b.png"],
237
- types: [CONTENT_TYPE_IMAGE_PNG, CONTENT_TYPE_IMAGE_PNG],
238
- });
239
- });
240
- });
241
-
242
- it("retains the expected sharepoint host fixture", () => {
243
- expect(SHAREPOINT_HOST).toBe("contoso.sharepoint.com");
244
- expect(TEST_URL_IMAGE).toContain(TEST_HOST);
245
- });
246
- });
@@ -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
- }