@openclaw/msteams 2026.5.2 → 2026.5.3-beta.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 (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,626 +0,0 @@
1
- import { Buffer } from "node:buffer";
2
- import { lookup } from "node:dns/promises";
3
- import {
4
- buildHostnameAllowlistPolicyFromSuffixAllowlist,
5
- isHttpsUrlAllowedByHostnameSuffixAllowlist,
6
- isPrivateIpAddress,
7
- normalizeHostnameSuffixAllowlist,
8
- type SsrFPolicy,
9
- } from "openclaw/plugin-sdk/ssrf-policy";
10
- import {
11
- isRecord,
12
- normalizeLowercaseStringOrEmpty,
13
- normalizeOptionalString,
14
- } from "openclaw/plugin-sdk/text-runtime";
15
- import type { MSTeamsAttachmentLike } from "./types.js";
16
-
17
- type InlineImageCandidate =
18
- | {
19
- kind: "data";
20
- data: Buffer;
21
- contentType?: string;
22
- placeholder: string;
23
- }
24
- | {
25
- kind: "url";
26
- url: string;
27
- contentType?: string;
28
- fileHint?: string;
29
- placeholder: string;
30
- };
31
-
32
- type InlineImageLimitOptions = {
33
- maxInlineBytes?: number;
34
- maxInlineTotalBytes?: number;
35
- };
36
-
37
- const IMAGE_EXT_RE = /\.(avif|bmp|gif|heic|heif|jpe?g|png|tiff?|webp)$/i;
38
-
39
- export const IMG_SRC_RE = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
40
- export const ATTACHMENT_TAG_RE = /<attachment[^>]+id=["']([^"']+)["'][^>]*>/gi;
41
-
42
- const DEFAULT_MEDIA_HOST_ALLOWLIST = [
43
- "graph.microsoft.com",
44
- "graph.microsoft.us",
45
- "graph.microsoft.de",
46
- "graph.microsoft.cn",
47
- "sharepoint.com",
48
- "sharepoint.us",
49
- "sharepoint.de",
50
- "sharepoint.cn",
51
- "sharepoint-df.com",
52
- "1drv.ms",
53
- "onedrive.com",
54
- "teams.microsoft.com",
55
- "teams.cdn.office.net",
56
- "statics.teams.cdn.office.net",
57
- "office.com",
58
- "office.net",
59
- // Azure Media Services / Skype CDN for clipboard-pasted images
60
- "asm.skype.com",
61
- "ams.skype.com",
62
- "media.ams.skype.com",
63
- // Bot Framework attachment URLs
64
- "trafficmanager.net",
65
- "blob.core.windows.net",
66
- "azureedge.net",
67
- "microsoft.com",
68
- ] as const;
69
-
70
- const DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST = [
71
- "api.botframework.com",
72
- "botframework.com",
73
- // Bot Framework Service URL (smba.trafficmanager.net) used for outbound
74
- // replies and inbound attachment downloads (clipboard-pasted images).
75
- "smba.trafficmanager.net",
76
- "graph.microsoft.com",
77
- "graph.microsoft.us",
78
- "graph.microsoft.de",
79
- "graph.microsoft.cn",
80
- ] as const;
81
-
82
- export const GRAPH_ROOT = "https://graph.microsoft.com/v1.0";
83
- export { isRecord };
84
-
85
- // Keep this local; importing the broad media-runtime SDK barrel pulls image/audio runtimes into
86
- // hot MSTeams attachment tests for one tiny estimator.
87
- export function estimateBase64DecodedBytes(base64: string): number {
88
- let effectiveLen = 0;
89
- for (let i = 0; i < base64.length; i += 1) {
90
- const code = base64.charCodeAt(i);
91
- if (code <= 0x20) {
92
- continue;
93
- }
94
- effectiveLen += 1;
95
- }
96
-
97
- if (effectiveLen === 0) {
98
- return 0;
99
- }
100
-
101
- let padding = 0;
102
- let end = base64.length - 1;
103
- while (end >= 0 && base64.charCodeAt(end) <= 0x20) {
104
- end -= 1;
105
- }
106
- if (end >= 0 && base64[end] === "=") {
107
- padding = 1;
108
- end -= 1;
109
- while (end >= 0 && base64.charCodeAt(end) <= 0x20) {
110
- end -= 1;
111
- }
112
- if (end >= 0 && base64[end] === "=") {
113
- padding = 2;
114
- }
115
- }
116
-
117
- const estimated = Math.floor((effectiveLen * 3) / 4) - padding;
118
- return Math.max(0, estimated);
119
- }
120
-
121
- /**
122
- * Host suffixes for SharePoint/OneDrive shared links that must be fetched via
123
- * the Graph `/shares/{shareId}/driveItem/content` endpoint instead of directly.
124
- *
125
- * Direct fetches of SharePoint/OneDrive shared URLs return empty/HTML landing
126
- * pages unless encoded as a Graph share id. See
127
- * https://learn.microsoft.com/en-us/graph/api/shares-get for the encoding.
128
- */
129
- const GRAPH_SHARED_LINK_HOST_SUFFIXES = [
130
- ".sharepoint.com",
131
- ".sharepoint.us",
132
- ".sharepoint.de",
133
- ".sharepoint.cn",
134
- ".sharepoint-df.com",
135
- "1drv.ms",
136
- "onedrive.live.com",
137
- "onedrive.com",
138
- ] as const;
139
-
140
- /**
141
- * Returns true when the URL points at a SharePoint or OneDrive host whose
142
- * shared-link content must be fetched through the Graph shares API rather
143
- * than directly.
144
- */
145
- export function isGraphSharedLinkUrl(url: string): boolean {
146
- let host: string;
147
- try {
148
- host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
149
- } catch {
150
- return false;
151
- }
152
- if (!host) {
153
- return false;
154
- }
155
- return GRAPH_SHARED_LINK_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(suffix));
156
- }
157
-
158
- /**
159
- * Encode a SharePoint/OneDrive URL as a Graph shareId using the documented
160
- * `u!` + base64url (no padding) scheme:
161
- * https://learn.microsoft.com/en-us/graph/api/shares-get#encoding-sharing-urls
162
- */
163
- export function encodeGraphShareId(url: string): string {
164
- // Buffer.from(...).toString("base64url") already returns base64url without
165
- // padding, matching the Graph spec exactly.
166
- return `u!${Buffer.from(url, "utf8").toString("base64url")}`;
167
- }
168
-
169
- /**
170
- * When `url` is a SharePoint/OneDrive shared link, return the matching
171
- * `GET /shares/{shareId}/driveItem/content` URL that actually yields the file
172
- * bytes. Returns `undefined` for non-shared-link URLs so callers can fall
173
- * through to the existing fetch path.
174
- */
175
- export function tryBuildGraphSharesUrlForSharedLink(url: string): string | undefined {
176
- if (!isGraphSharedLinkUrl(url)) {
177
- return undefined;
178
- }
179
- return `${GRAPH_ROOT}/shares/${encodeGraphShareId(url)}/driveItem/content`;
180
- }
181
-
182
- export function readNestedString(value: unknown, keys: Array<string | number>): string | undefined {
183
- let current: unknown = value;
184
- for (const key of keys) {
185
- if (!isRecord(current)) {
186
- return undefined;
187
- }
188
- current = current[key as keyof typeof current];
189
- }
190
- return normalizeOptionalString(current);
191
- }
192
-
193
- export function resolveRequestUrl(input: RequestInfo | URL): string {
194
- if (typeof input === "string") {
195
- return input;
196
- }
197
- if (input instanceof URL) {
198
- return input.toString();
199
- }
200
- if (typeof input === "object" && input && "url" in input && typeof input.url === "string") {
201
- return input.url;
202
- }
203
- try {
204
- return JSON.stringify(input);
205
- } catch {
206
- return "";
207
- }
208
- }
209
-
210
- export function normalizeContentType(value: unknown): string | undefined {
211
- if (typeof value !== "string") {
212
- return undefined;
213
- }
214
- const trimmed = value.trim();
215
- return trimmed ? trimmed : undefined;
216
- }
217
-
218
- export function inferPlaceholder(params: {
219
- contentType?: string;
220
- fileName?: string;
221
- fileType?: string;
222
- }): string {
223
- const mime = normalizeLowercaseStringOrEmpty(params.contentType ?? "");
224
- const name = normalizeLowercaseStringOrEmpty(params.fileName ?? "");
225
- const fileType = normalizeLowercaseStringOrEmpty(params.fileType ?? "");
226
-
227
- const looksLikeImage =
228
- mime.startsWith("image/") || IMAGE_EXT_RE.test(name) || IMAGE_EXT_RE.test(`x.${fileType}`);
229
-
230
- return looksLikeImage ? "<media:image>" : "<media:document>";
231
- }
232
-
233
- export function isLikelyImageAttachment(att: MSTeamsAttachmentLike): boolean {
234
- const contentType = normalizeContentType(att.contentType) ?? "";
235
- const name = typeof att.name === "string" ? att.name : "";
236
- if (contentType.startsWith("image/")) {
237
- return true;
238
- }
239
- if (IMAGE_EXT_RE.test(name)) {
240
- return true;
241
- }
242
-
243
- if (
244
- contentType === "application/vnd.microsoft.teams.file.download.info" &&
245
- isRecord(att.content)
246
- ) {
247
- const fileType = typeof att.content.fileType === "string" ? att.content.fileType : "";
248
- if (fileType && IMAGE_EXT_RE.test(`x.${fileType}`)) {
249
- return true;
250
- }
251
- const fileName = typeof att.content.fileName === "string" ? att.content.fileName : "";
252
- if (fileName && IMAGE_EXT_RE.test(fileName)) {
253
- return true;
254
- }
255
- }
256
-
257
- return false;
258
- }
259
-
260
- /**
261
- * Returns true if the attachment can be downloaded (any file type).
262
- * Used when downloading all files, not just images.
263
- */
264
- export function isDownloadableAttachment(att: MSTeamsAttachmentLike): boolean {
265
- const contentType = normalizeContentType(att.contentType) ?? "";
266
-
267
- // Teams file download info always has a downloadUrl
268
- if (
269
- contentType === "application/vnd.microsoft.teams.file.download.info" &&
270
- isRecord(att.content) &&
271
- typeof att.content.downloadUrl === "string"
272
- ) {
273
- return true;
274
- }
275
-
276
- // Any attachment with a contentUrl can be downloaded
277
- if (typeof att.contentUrl === "string" && att.contentUrl.trim()) {
278
- return true;
279
- }
280
-
281
- return false;
282
- }
283
-
284
- function isHtmlAttachment(att: MSTeamsAttachmentLike): boolean {
285
- const contentType = normalizeContentType(att.contentType) ?? "";
286
- return contentType.startsWith("text/html");
287
- }
288
-
289
- export function extractHtmlFromAttachment(att: MSTeamsAttachmentLike): string | undefined {
290
- if (!isHtmlAttachment(att)) {
291
- return undefined;
292
- }
293
- if (typeof att.content === "string") {
294
- return att.content;
295
- }
296
- if (!isRecord(att.content)) {
297
- return undefined;
298
- }
299
- const text =
300
- typeof att.content.text === "string"
301
- ? att.content.text
302
- : typeof att.content.body === "string"
303
- ? att.content.body
304
- : typeof att.content.content === "string"
305
- ? att.content.content
306
- : undefined;
307
- return text;
308
- }
309
-
310
- function isLikelyBase64Payload(value: string): boolean {
311
- return /^[A-Za-z0-9+/=\r\n]+$/.test(value);
312
- }
313
-
314
- function decodeDataImageWithLimits(
315
- src: string,
316
- opts: { maxInlineBytes?: number },
317
- ): { candidate: InlineImageCandidate | null; estimatedBytes: number } {
318
- const match = /^data:(image\/[a-z0-9.+-]+)?(;base64)?,(.*)$/i.exec(src);
319
- if (!match) {
320
- return { candidate: null, estimatedBytes: 0 };
321
- }
322
- const contentType = normalizeLowercaseStringOrEmpty(match[1] ?? "");
323
- const isBase64 = Boolean(match[2]);
324
- if (!isBase64) {
325
- return { candidate: null, estimatedBytes: 0 };
326
- }
327
- const payload = match[3] ?? "";
328
- if (!payload || !isLikelyBase64Payload(payload)) {
329
- return { candidate: null, estimatedBytes: 0 };
330
- }
331
-
332
- const estimatedBytes = estimateBase64DecodedBytes(payload);
333
- if (estimatedBytes <= 0) {
334
- return { candidate: null, estimatedBytes: 0 };
335
- }
336
- if (typeof opts.maxInlineBytes === "number" && estimatedBytes > opts.maxInlineBytes) {
337
- return { candidate: null, estimatedBytes };
338
- }
339
-
340
- try {
341
- const data = Buffer.from(payload, "base64");
342
- return {
343
- candidate: { kind: "data", data, contentType, placeholder: "<media:image>" },
344
- estimatedBytes,
345
- };
346
- } catch {
347
- return { candidate: null, estimatedBytes: 0 };
348
- }
349
- }
350
-
351
- function fileHintFromUrl(src: string): string | undefined {
352
- try {
353
- const url = new URL(src);
354
- const name = url.pathname.split("/").pop();
355
- return name || undefined;
356
- } catch {
357
- return undefined;
358
- }
359
- }
360
-
361
- export function extractInlineImageCandidates(
362
- attachments: MSTeamsAttachmentLike[],
363
- limits?: InlineImageLimitOptions,
364
- ): InlineImageCandidate[] {
365
- const out: InlineImageCandidate[] = [];
366
- let totalEstimatedInlineBytes = 0;
367
- outerLoop: for (const att of attachments) {
368
- const html = extractHtmlFromAttachment(att);
369
- if (!html) {
370
- continue;
371
- }
372
- IMG_SRC_RE.lastIndex = 0;
373
- let match: RegExpExecArray | null = IMG_SRC_RE.exec(html);
374
- while (match) {
375
- const src = match[1]?.trim();
376
- if (src && !src.startsWith("cid:")) {
377
- if (src.startsWith("data:")) {
378
- const { candidate: decoded, estimatedBytes } = decodeDataImageWithLimits(src, {
379
- maxInlineBytes: limits?.maxInlineBytes,
380
- });
381
- if (decoded) {
382
- const nextTotal = totalEstimatedInlineBytes + estimatedBytes;
383
- if (
384
- typeof limits?.maxInlineTotalBytes === "number" &&
385
- nextTotal > limits.maxInlineTotalBytes
386
- ) {
387
- break outerLoop;
388
- }
389
- totalEstimatedInlineBytes = nextTotal;
390
- out.push(decoded);
391
- }
392
- } else {
393
- out.push({
394
- kind: "url",
395
- url: src,
396
- fileHint: fileHintFromUrl(src),
397
- placeholder: "<media:image>",
398
- });
399
- }
400
- }
401
- match = IMG_SRC_RE.exec(html);
402
- }
403
- }
404
- return out;
405
- }
406
-
407
- export function safeHostForUrl(url: string): string {
408
- try {
409
- return normalizeLowercaseStringOrEmpty(new URL(url).hostname);
410
- } catch {
411
- return "invalid-url";
412
- }
413
- }
414
-
415
- export function resolveAllowedHosts(input?: string[]): string[] {
416
- return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_HOST_ALLOWLIST);
417
- }
418
-
419
- export function resolveAuthAllowedHosts(input?: string[]): string[] {
420
- return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST);
421
- }
422
-
423
- export type MSTeamsAttachmentFetchPolicy = {
424
- allowHosts: string[];
425
- authAllowHosts: string[];
426
- };
427
-
428
- /**
429
- * Logger surface for attachment download errors. Structured so callers can
430
- * pass `MSTeamsMonitorLogger` directly without adapters. Optional `warn`/
431
- * `error` methods prevent silent swallowing of fetch failures — see issue
432
- * #63396 where empty `catch {}` blocks hid a Node 24+ undici incompatibility.
433
- */
434
- export type MSTeamsAttachmentDownloadLogger = {
435
- warn?: (message: string, meta?: Record<string, unknown>) => void;
436
- error?: (message: string, meta?: Record<string, unknown>) => void;
437
- };
438
-
439
- export type MSTeamsAttachmentResolveFn = (hostname: string) => Promise<{ address: string }>;
440
-
441
- export function resolveAttachmentFetchPolicy(params?: {
442
- allowHosts?: string[];
443
- authAllowHosts?: string[];
444
- }): MSTeamsAttachmentFetchPolicy {
445
- return {
446
- allowHosts: resolveAllowedHosts(params?.allowHosts),
447
- authAllowHosts: resolveAuthAllowedHosts(params?.authAllowHosts),
448
- };
449
- }
450
-
451
- export function isUrlAllowed(url: string, allowlist: string[]): boolean {
452
- return isHttpsUrlAllowedByHostnameSuffixAllowlist(url, allowlist);
453
- }
454
-
455
- export function applyAuthorizationHeaderForUrl(params: {
456
- headers: Headers;
457
- url: string;
458
- authAllowHosts: string[];
459
- bearerToken?: string;
460
- }): void {
461
- if (!params.bearerToken) {
462
- params.headers.delete("Authorization");
463
- return;
464
- }
465
- if (isUrlAllowed(params.url, params.authAllowHosts)) {
466
- params.headers.set("Authorization", `Bearer ${params.bearerToken}`);
467
- return;
468
- }
469
- params.headers.delete("Authorization");
470
- }
471
-
472
- export function resolveMediaSsrfPolicy(allowHosts: string[]): SsrFPolicy | undefined {
473
- return buildHostnameAllowlistPolicyFromSuffixAllowlist(allowHosts);
474
- }
475
-
476
- /**
477
- * Returns true if the given IPv4 or IPv6 address is in a private, loopback,
478
- * or link-local range that must never be reached from media downloads.
479
- *
480
- * Delegates to the SDK's `isPrivateIpAddress` which handles IPv4-mapped IPv6,
481
- * expanded notation, NAT64, 6to4, Teredo, octal IPv4, and fails closed on
482
- * parse errors.
483
- */
484
- export const isPrivateOrReservedIP: (ip: string) => boolean = isPrivateIpAddress;
485
-
486
- /**
487
- * Resolve a hostname via DNS and reject private/reserved IPs.
488
- * Throws if the resolved IP is private or resolution fails.
489
- */
490
- export async function resolveAndValidateIP(
491
- hostname: string,
492
- resolveFn?: MSTeamsAttachmentResolveFn,
493
- ): Promise<string> {
494
- const resolve = resolveFn ?? lookup;
495
- let resolved: { address: string };
496
- try {
497
- resolved = await resolve(hostname);
498
- } catch {
499
- throw new Error(`DNS resolution failed for "${hostname}"`);
500
- }
501
- if (isPrivateOrReservedIP(resolved.address)) {
502
- throw new Error(`Hostname "${hostname}" resolves to private/reserved IP (${resolved.address})`);
503
- }
504
- return resolved.address;
505
- }
506
-
507
- /** Maximum number of redirects to follow in safeFetch. */
508
- const MAX_SAFE_REDIRECTS = 5;
509
-
510
- /**
511
- * Fetch a URL with redirect: "manual", validating each redirect target
512
- * against the hostname allowlist and optional DNS-resolved IP (anti-SSRF).
513
- *
514
- * This prevents:
515
- * - Auto-following redirects to non-allowlisted hosts
516
- * - DNS rebinding attacks when a lookup function is provided
517
- */
518
- export async function safeFetch(params: {
519
- url: string;
520
- allowHosts: string[];
521
- /**
522
- * Optional allowlist for forwarding Authorization across redirects.
523
- * When set, Authorization is stripped before following redirects to hosts
524
- * outside this list.
525
- */
526
- authorizationAllowHosts?: string[];
527
- fetchFn?: typeof fetch;
528
- requestInit?: RequestInit;
529
- resolveFn?: MSTeamsAttachmentResolveFn;
530
- }): Promise<Response> {
531
- const fetchFn = params.fetchFn ?? fetch;
532
- const resolveFn = params.resolveFn ?? lookup;
533
- const hasDispatcher = Boolean(
534
- params.requestInit &&
535
- typeof params.requestInit === "object" &&
536
- "dispatcher" in (params.requestInit as Record<string, unknown>),
537
- );
538
- const currentHeaders = new Headers(params.requestInit?.headers);
539
- let currentUrl = params.url;
540
-
541
- if (!isUrlAllowed(currentUrl, params.allowHosts)) {
542
- throw new Error(`Initial download URL blocked: ${currentUrl}`);
543
- }
544
-
545
- if (resolveFn) {
546
- try {
547
- const initialHost = new URL(currentUrl).hostname;
548
- await resolveAndValidateIP(initialHost, resolveFn);
549
- } catch {
550
- throw new Error(`Initial download URL blocked: ${currentUrl}`);
551
- }
552
- }
553
-
554
- for (let i = 0; i <= MAX_SAFE_REDIRECTS; i++) {
555
- const res = await fetchFn(currentUrl, {
556
- ...params.requestInit,
557
- headers: currentHeaders,
558
- redirect: "manual",
559
- });
560
-
561
- if (![301, 302, 303, 307, 308].includes(res.status)) {
562
- return res;
563
- }
564
-
565
- const location = res.headers.get("location");
566
- if (!location) {
567
- return res;
568
- }
569
-
570
- let redirectUrl: string;
571
- try {
572
- redirectUrl = new URL(location, currentUrl).toString();
573
- } catch {
574
- throw new Error(`Invalid redirect URL: ${location}`);
575
- }
576
-
577
- // Validate redirect target against hostname allowlist
578
- if (!isUrlAllowed(redirectUrl, params.allowHosts)) {
579
- throw new Error(`Media redirect target blocked by allowlist: ${redirectUrl}`);
580
- }
581
-
582
- // Prevent credential bleed: only keep Authorization on redirect hops that
583
- // are explicitly auth-allowlisted.
584
- if (
585
- currentHeaders.has("authorization") &&
586
- params.authorizationAllowHosts &&
587
- !isUrlAllowed(redirectUrl, params.authorizationAllowHosts)
588
- ) {
589
- currentHeaders.delete("authorization");
590
- }
591
-
592
- // When a pinned dispatcher is already injected by an upstream guard
593
- // (for example fetchWithSsrFGuard), let that guard own redirect handling
594
- // after this allowlist validation step.
595
- if (hasDispatcher) {
596
- return res;
597
- }
598
-
599
- // Validate redirect target's resolved IP
600
- if (resolveFn) {
601
- const redirectHost = new URL(redirectUrl).hostname;
602
- await resolveAndValidateIP(redirectHost, resolveFn);
603
- }
604
-
605
- currentUrl = redirectUrl;
606
- }
607
-
608
- throw new Error(`Too many redirects (>${MAX_SAFE_REDIRECTS})`);
609
- }
610
-
611
- export async function safeFetchWithPolicy(params: {
612
- url: string;
613
- policy: MSTeamsAttachmentFetchPolicy;
614
- fetchFn?: typeof fetch;
615
- requestInit?: RequestInit;
616
- resolveFn?: MSTeamsAttachmentResolveFn;
617
- }): Promise<Response> {
618
- return await safeFetch({
619
- url: params.url,
620
- allowHosts: params.policy.allowHosts,
621
- authorizationAllowHosts: params.policy.authAllowHosts,
622
- fetchFn: params.fetchFn,
623
- requestInit: params.requestInit,
624
- resolveFn: params.resolveFn,
625
- });
626
- }
@@ -1,47 +0,0 @@
1
- export type MSTeamsAttachmentLike = {
2
- contentType?: string | null;
3
- contentUrl?: string | null;
4
- name?: string | null;
5
- thumbnailUrl?: string | null;
6
- content?: unknown;
7
- };
8
-
9
- export type MSTeamsAccessTokenProvider = {
10
- getAccessToken: (scope: string) => Promise<string>;
11
- };
12
-
13
- export type MSTeamsInboundMedia = {
14
- path: string;
15
- contentType?: string;
16
- placeholder: string;
17
- };
18
-
19
- export type MSTeamsHtmlAttachmentSummary = {
20
- htmlAttachments: number;
21
- imgTags: number;
22
- dataImages: number;
23
- cidImages: number;
24
- srcHosts: string[];
25
- attachmentTags: number;
26
- attachmentIds: string[];
27
- };
28
-
29
- export type MSTeamsGraphMediaResult = {
30
- media: MSTeamsInboundMedia[];
31
- hostedCount?: number;
32
- attachmentCount?: number;
33
- hostedStatus?: number;
34
- attachmentStatus?: number;
35
- messageUrl?: string;
36
- tokenError?: boolean;
37
- };
38
-
39
- /**
40
- * Narrow logger surface used by `downloadMSTeamsGraphMedia` for diagnostic
41
- * events. Accepting an optional callback keeps the helper testable without
42
- * pulling in the full channel logger type, while still allowing the monitor
43
- * handler to forward its plugin logger.
44
- */
45
- export type MSTeamsGraphMediaLogger = {
46
- debug?: (message: string, meta?: Record<string, unknown>) => void;
47
- };