@kodelyth/msteams 2026.5.39 → 2026.5.42

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 (208) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/dist/api.js +3 -0
  7. package/dist/channel-BvTXHuGs.js +1161 -0
  8. package/dist/channel-config-api.js +2 -0
  9. package/dist/channel-plugin-api.js +2 -0
  10. package/dist/channel.runtime-NssGKZm5.js +650 -0
  11. package/dist/config-schema-Btk-XCOd.js +43 -0
  12. package/dist/contract-api.js +2 -0
  13. package/dist/graph-users-D-gKCguI.js +1411 -0
  14. package/dist/index.js +22 -0
  15. package/dist/oauth-BUxlphX3.js +114 -0
  16. package/dist/oauth.token-ebId9946.js +116 -0
  17. package/dist/probe-Cj2KsAGF.js +2190 -0
  18. package/dist/runtime-api-BL4DOWXD.js +28 -0
  19. package/dist/runtime-api.js +2 -0
  20. package/dist/secret-contract-Bo7kdUrT.js +35 -0
  21. package/dist/secret-contract-api.js +2 -0
  22. package/dist/setup-entry.js +15 -0
  23. package/dist/setup-plugin-api.js +64 -0
  24. package/dist/setup-surface-COTQDcTQ.js +531 -0
  25. package/dist/src-tvpsGYPV.js +4226 -0
  26. package/dist/test-api.js +2 -0
  27. package/index.ts +20 -0
  28. package/klaw.plugin.json +2 -726
  29. package/package.json +4 -4
  30. package/runtime-api.ts +66 -0
  31. package/secret-contract-api.ts +5 -0
  32. package/setup-entry.ts +13 -0
  33. package/setup-plugin-api.ts +3 -0
  34. package/src/ai-entity.ts +7 -0
  35. package/src/approval-auth.ts +44 -0
  36. package/src/attachments/bot-framework.test.ts +506 -0
  37. package/src/attachments/bot-framework.ts +348 -0
  38. package/src/attachments/download.ts +328 -0
  39. package/src/attachments/graph.test.ts +441 -0
  40. package/src/attachments/graph.ts +489 -0
  41. package/src/attachments/html.ts +122 -0
  42. package/src/attachments/payload.ts +14 -0
  43. package/src/attachments/remote-media.test.ts +187 -0
  44. package/src/attachments/remote-media.ts +86 -0
  45. package/src/attachments/shared.test.ts +547 -0
  46. package/src/attachments/shared.ts +655 -0
  47. package/src/attachments/types.ts +47 -0
  48. package/src/attachments.graph.test.ts +414 -0
  49. package/src/attachments.helpers.test.ts +245 -0
  50. package/src/attachments.test-helpers.ts +17 -0
  51. package/src/attachments.test.ts +754 -0
  52. package/src/attachments.ts +18 -0
  53. package/src/block-streaming-config.test.ts +61 -0
  54. package/src/channel-api.ts +1 -0
  55. package/src/channel.actions.test.ts +797 -0
  56. package/src/channel.directory.test.ts +176 -0
  57. package/src/channel.message-adapter.test.ts +227 -0
  58. package/src/channel.runtime.ts +56 -0
  59. package/src/channel.setup.ts +77 -0
  60. package/src/channel.test.ts +136 -0
  61. package/src/channel.ts +1176 -0
  62. package/src/config-schema.ts +6 -0
  63. package/src/config-ui-hints.ts +40 -0
  64. package/src/conversation-store-fs.test.ts +81 -0
  65. package/src/conversation-store-fs.ts +149 -0
  66. package/src/conversation-store-helpers.test.ts +202 -0
  67. package/src/conversation-store-helpers.ts +105 -0
  68. package/src/conversation-store-memory.ts +51 -0
  69. package/src/conversation-store.shared.test.ts +260 -0
  70. package/src/conversation-store.ts +71 -0
  71. package/src/directory-live.test.ts +156 -0
  72. package/src/directory-live.ts +111 -0
  73. package/src/doctor.ts +27 -0
  74. package/src/errors.test.ts +154 -0
  75. package/src/errors.ts +270 -0
  76. package/src/feedback-reflection-prompt.ts +117 -0
  77. package/src/feedback-reflection-store.ts +113 -0
  78. package/src/feedback-reflection.test.ts +237 -0
  79. package/src/feedback-reflection.ts +268 -0
  80. package/src/file-consent-helpers.test.ts +328 -0
  81. package/src/file-consent-helpers.ts +115 -0
  82. package/src/file-consent-invoke.ts +150 -0
  83. package/src/file-consent.test.ts +378 -0
  84. package/src/file-consent.ts +223 -0
  85. package/src/graph-chat.ts +36 -0
  86. package/src/graph-group-management.test.ts +332 -0
  87. package/src/graph-group-management.ts +168 -0
  88. package/src/graph-members.test.ts +89 -0
  89. package/src/graph-members.ts +48 -0
  90. package/src/graph-messages.actions.test.ts +253 -0
  91. package/src/graph-messages.read.test.ts +391 -0
  92. package/src/graph-messages.search.test.ts +227 -0
  93. package/src/graph-messages.test-helpers.ts +50 -0
  94. package/src/graph-messages.ts +534 -0
  95. package/src/graph-teams.test.ts +222 -0
  96. package/src/graph-teams.ts +114 -0
  97. package/src/graph-thread.test.ts +252 -0
  98. package/src/graph-thread.ts +146 -0
  99. package/src/graph-upload.test.ts +253 -0
  100. package/src/graph-upload.ts +531 -0
  101. package/src/graph-users.ts +29 -0
  102. package/src/graph.test.ts +540 -0
  103. package/src/graph.ts +308 -0
  104. package/src/inbound.test.ts +221 -0
  105. package/src/inbound.ts +148 -0
  106. package/src/index.ts +4 -0
  107. package/src/media-helpers.test.ts +220 -0
  108. package/src/media-helpers.ts +105 -0
  109. package/src/mentions.test.ts +254 -0
  110. package/src/mentions.ts +114 -0
  111. package/src/messenger.test.ts +961 -0
  112. package/src/messenger.ts +608 -0
  113. package/src/monitor-handler/access.ts +136 -0
  114. package/src/monitor-handler/inbound-media.test.ts +314 -0
  115. package/src/monitor-handler/inbound-media.ts +180 -0
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  117. package/src/monitor-handler/message-handler.authz.test.ts +739 -0
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  119. package/src/monitor-handler/message-handler.test-support.ts +99 -0
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +225 -0
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +132 -0
  122. package/src/monitor-handler/message-handler.ts +1003 -0
  123. package/src/monitor-handler/reaction-handler.test.ts +325 -0
  124. package/src/monitor-handler/reaction-handler.ts +122 -0
  125. package/src/monitor-handler/thread-session.ts +30 -0
  126. package/src/monitor-handler.adaptive-card.test.ts +158 -0
  127. package/src/monitor-handler.feedback-authz.test.ts +357 -0
  128. package/src/monitor-handler.file-consent.test.ts +443 -0
  129. package/src/monitor-handler.sso.test.ts +576 -0
  130. package/src/monitor-handler.test-helpers.ts +181 -0
  131. package/src/monitor-handler.ts +538 -0
  132. package/src/monitor-handler.types.ts +27 -0
  133. package/src/monitor-types.ts +6 -0
  134. package/src/monitor.lifecycle.test.ts +457 -0
  135. package/src/monitor.test.ts +119 -0
  136. package/src/monitor.ts +476 -0
  137. package/src/oauth.flow.ts +77 -0
  138. package/src/oauth.shared.ts +37 -0
  139. package/src/oauth.test.ts +350 -0
  140. package/src/oauth.token.ts +162 -0
  141. package/src/oauth.ts +130 -0
  142. package/src/outbound.test.ts +400 -0
  143. package/src/outbound.ts +198 -0
  144. package/src/pending-uploads-fs.test.ts +261 -0
  145. package/src/pending-uploads-fs.ts +235 -0
  146. package/src/pending-uploads.test.ts +186 -0
  147. package/src/pending-uploads.ts +121 -0
  148. package/src/policy.test.ts +156 -0
  149. package/src/policy.ts +245 -0
  150. package/src/polls-store-memory.ts +32 -0
  151. package/src/polls.test.ts +169 -0
  152. package/src/polls.ts +312 -0
  153. package/src/presentation.ts +93 -0
  154. package/src/probe.test.ts +79 -0
  155. package/src/probe.ts +132 -0
  156. package/src/reply-dispatcher.test.ts +543 -0
  157. package/src/reply-dispatcher.ts +523 -0
  158. package/src/reply-stream-controller.test.ts +424 -0
  159. package/src/reply-stream-controller.ts +334 -0
  160. package/src/resolve-allowlist.test.ts +253 -0
  161. package/src/resolve-allowlist.ts +309 -0
  162. package/src/revoked-context.ts +17 -0
  163. package/src/runtime.ts +12 -0
  164. package/src/sdk-types.ts +59 -0
  165. package/src/sdk.test.ts +727 -0
  166. package/src/sdk.ts +916 -0
  167. package/src/secret-contract.ts +49 -0
  168. package/src/secret-input.ts +7 -0
  169. package/src/send-context.test.ts +93 -0
  170. package/src/send-context.ts +269 -0
  171. package/src/send.test.ts +588 -0
  172. package/src/send.ts +697 -0
  173. package/src/sent-message-cache.test.ts +106 -0
  174. package/src/sent-message-cache.ts +174 -0
  175. package/src/session-route.ts +40 -0
  176. package/src/setup-core.ts +162 -0
  177. package/src/setup-surface.test.ts +175 -0
  178. package/src/setup-surface.ts +319 -0
  179. package/src/sso-token-store.test.ts +74 -0
  180. package/src/sso-token-store.ts +166 -0
  181. package/src/sso.ts +300 -0
  182. package/src/storage.ts +25 -0
  183. package/src/store-fs.ts +42 -0
  184. package/src/streaming-message.test.ts +323 -0
  185. package/src/streaming-message.ts +327 -0
  186. package/src/test-runtime.ts +16 -0
  187. package/src/thread-parent-context.test.ts +224 -0
  188. package/src/thread-parent-context.ts +159 -0
  189. package/src/token-response.ts +11 -0
  190. package/src/token.test.ts +268 -0
  191. package/src/token.ts +194 -0
  192. package/src/user-agent.test.ts +121 -0
  193. package/src/user-agent.ts +53 -0
  194. package/src/webhook-timeouts.ts +27 -0
  195. package/src/welcome-card.test.ts +104 -0
  196. package/src/welcome-card.ts +57 -0
  197. package/test-api.ts +1 -0
  198. package/tsconfig.json +16 -0
  199. package/api.js +0 -7
  200. package/channel-config-api.js +0 -7
  201. package/channel-plugin-api.js +0 -7
  202. package/contract-api.js +0 -7
  203. package/index.js +0 -7
  204. package/runtime-api.js +0 -7
  205. package/secret-contract-api.js +0 -7
  206. package/setup-entry.js +0 -7
  207. package/setup-plugin-api.js +0 -7
  208. package/test-api.js +0 -7
@@ -0,0 +1,1411 @@
1
+ import { M as getMSTeamsRuntime, h as fetchWithSsrFGuard$1 } from "./runtime-api-BL4DOWXD.js";
2
+ import { n as refreshMSTeamsDelegatedTokens } from "./oauth.token-ebId9946.js";
3
+ import { createRequire } from "node:module";
4
+ import { isRecord as isRecord$2, normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
5
+ import { fetchWithSsrFGuard } from "klaw/plugin-sdk/ssrf-runtime";
6
+ import { readProviderJsonResponse } from "klaw/plugin-sdk/provider-http";
7
+ import { Buffer } from "node:buffer";
8
+ import { lookup } from "node:dns/promises";
9
+ import { buildHostnameAllowlistPolicyFromSuffixAllowlist, isHttpsUrlAllowedByHostnameSuffixAllowlist, isPrivateIpAddress, normalizeHostnameSuffixAllowlist } from "klaw/plugin-sdk/ssrf-policy";
10
+ import * as fs from "node:fs";
11
+ import { readFileSync } from "node:fs";
12
+ import path, { basename, dirname } from "node:path";
13
+ import { privateFileStoreSync } from "klaw/plugin-sdk/security-runtime";
14
+ import { hasConfiguredSecretInput, normalizeResolvedSecretInputString, normalizeSecretInputString } from "klaw/plugin-sdk/secret-input";
15
+ //#region extensions/msteams/src/attachments/shared.ts
16
+ const IMAGE_EXT_RE = /\.(avif|bmp|gif|heic|heif|jpe?g|png|tiff?|webp)$/i;
17
+ const IMG_SRC_RE = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
18
+ const ATTACHMENT_TAG_RE = /<attachment[^>]+id=["']([^"']+)["'][^>]*>/gi;
19
+ const DEFAULT_MEDIA_HOST_ALLOWLIST = [
20
+ "graph.microsoft.com",
21
+ "graph.microsoft.us",
22
+ "graph.microsoft.de",
23
+ "graph.microsoft.cn",
24
+ "sharepoint.com",
25
+ "sharepoint.us",
26
+ "sharepoint.de",
27
+ "sharepoint.cn",
28
+ "sharepoint-df.com",
29
+ "1drv.ms",
30
+ "onedrive.com",
31
+ "teams.microsoft.com",
32
+ "teams.cdn.office.net",
33
+ "statics.teams.cdn.office.net",
34
+ "office.com",
35
+ "office.net",
36
+ "asm.skype.com",
37
+ "ams.skype.com",
38
+ "media.ams.skype.com",
39
+ "trafficmanager.net",
40
+ "blob.core.windows.net",
41
+ "azureedge.net",
42
+ "microsoft.com"
43
+ ];
44
+ const DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST = [
45
+ "api.botframework.com",
46
+ "botframework.com",
47
+ "smba.trafficmanager.net",
48
+ "graph.microsoft.com",
49
+ "graph.microsoft.us",
50
+ "graph.microsoft.de",
51
+ "graph.microsoft.cn"
52
+ ];
53
+ const GRAPH_ROOT = "https://graph.microsoft.com/v1.0";
54
+ function estimateBase64DecodedBytes(base64) {
55
+ let effectiveLen = 0;
56
+ for (let i = 0; i < base64.length; i += 1) {
57
+ if (base64.charCodeAt(i) <= 32) continue;
58
+ effectiveLen += 1;
59
+ }
60
+ if (effectiveLen === 0) return 0;
61
+ let padding = 0;
62
+ let end = base64.length - 1;
63
+ while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
64
+ if (end >= 0 && base64[end] === "=") {
65
+ padding = 1;
66
+ end -= 1;
67
+ while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
68
+ if (end >= 0 && base64[end] === "=") padding = 2;
69
+ }
70
+ const estimated = Math.floor(effectiveLen * 3 / 4) - padding;
71
+ return Math.max(0, estimated);
72
+ }
73
+ /**
74
+ * Host suffixes for SharePoint/OneDrive shared links that must be fetched via
75
+ * the Graph `/shares/{shareId}/driveItem/content` endpoint instead of directly.
76
+ *
77
+ * Direct fetches of SharePoint/OneDrive shared URLs return empty/HTML landing
78
+ * pages unless encoded as a Graph share id. See
79
+ * https://learn.microsoft.com/en-us/graph/api/shares-get for the encoding.
80
+ */
81
+ const GRAPH_SHARED_LINK_HOST_SUFFIXES = [
82
+ ".sharepoint.com",
83
+ ".sharepoint.us",
84
+ ".sharepoint.de",
85
+ ".sharepoint.cn",
86
+ ".sharepoint-df.com",
87
+ "1drv.ms",
88
+ "onedrive.live.com",
89
+ "onedrive.com"
90
+ ];
91
+ /**
92
+ * Returns true when the URL points at a SharePoint or OneDrive host whose
93
+ * shared-link content must be fetched through the Graph shares API rather
94
+ * than directly.
95
+ */
96
+ function isGraphSharedLinkUrl(url) {
97
+ let host;
98
+ try {
99
+ host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
100
+ } catch {
101
+ return false;
102
+ }
103
+ if (!host) return false;
104
+ return GRAPH_SHARED_LINK_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(suffix));
105
+ }
106
+ /**
107
+ * Encode a SharePoint/OneDrive URL as a Graph shareId using the documented
108
+ * `u!` + base64url (no padding) scheme:
109
+ * https://learn.microsoft.com/en-us/graph/api/shares-get#encoding-sharing-urls
110
+ */
111
+ function encodeGraphShareId(url) {
112
+ return `u!${Buffer.from(url, "utf8").toString("base64url")}`;
113
+ }
114
+ /**
115
+ * When `url` is a SharePoint/OneDrive shared link, return the matching
116
+ * `GET /shares/{shareId}/driveItem/content` URL that actually yields the file
117
+ * bytes. Returns `undefined` for non-shared-link URLs so callers can fall
118
+ * through to the existing fetch path.
119
+ */
120
+ function tryBuildGraphSharesUrlForSharedLink(url) {
121
+ if (!isGraphSharedLinkUrl(url)) return;
122
+ return `${GRAPH_ROOT}/shares/${encodeGraphShareId(url)}/driveItem/content`;
123
+ }
124
+ function readNestedString(value, keys) {
125
+ let current = value;
126
+ for (const key of keys) {
127
+ if (!isRecord$2(current)) return;
128
+ current = current[key];
129
+ }
130
+ return normalizeOptionalString(current);
131
+ }
132
+ function resolveRequestUrl(input) {
133
+ if (typeof input === "string") return input;
134
+ if (input instanceof URL) return input.toString();
135
+ if (typeof input === "object" && input && "url" in input && typeof input.url === "string") return input.url;
136
+ try {
137
+ return JSON.stringify(input);
138
+ } catch {
139
+ return "";
140
+ }
141
+ }
142
+ function normalizeContentType(value) {
143
+ if (typeof value !== "string") return;
144
+ const trimmed = value.trim();
145
+ return trimmed ? trimmed : void 0;
146
+ }
147
+ function inferPlaceholder(params) {
148
+ const mime = normalizeLowercaseStringOrEmpty(params.contentType ?? "");
149
+ const name = normalizeLowercaseStringOrEmpty(params.fileName ?? "");
150
+ const fileType = normalizeLowercaseStringOrEmpty(params.fileType ?? "");
151
+ return mime.startsWith("image/") || IMAGE_EXT_RE.test(name) || IMAGE_EXT_RE.test(`x.${fileType}`) ? "<media:image>" : "<media:document>";
152
+ }
153
+ function isLikelyImageAttachment(att) {
154
+ const contentType = normalizeContentType(att.contentType) ?? "";
155
+ const name = typeof att.name === "string" ? att.name : "";
156
+ if (contentType.startsWith("image/")) return true;
157
+ if (IMAGE_EXT_RE.test(name)) return true;
158
+ if (contentType === "application/vnd.microsoft.teams.file.download.info" && isRecord$2(att.content)) {
159
+ const fileType = typeof att.content.fileType === "string" ? att.content.fileType : "";
160
+ if (fileType && IMAGE_EXT_RE.test(`x.${fileType}`)) return true;
161
+ const fileName = typeof att.content.fileName === "string" ? att.content.fileName : "";
162
+ if (fileName && IMAGE_EXT_RE.test(fileName)) return true;
163
+ }
164
+ return false;
165
+ }
166
+ /**
167
+ * Returns true if the attachment can be downloaded (any file type).
168
+ * Used when downloading all files, not just images.
169
+ */
170
+ function isDownloadableAttachment(att) {
171
+ if ((normalizeContentType(att.contentType) ?? "") === "application/vnd.microsoft.teams.file.download.info" && isRecord$2(att.content) && typeof att.content.downloadUrl === "string") return true;
172
+ if (typeof att.contentUrl === "string" && att.contentUrl.trim()) return true;
173
+ return false;
174
+ }
175
+ function isHtmlAttachment(att) {
176
+ return (normalizeContentType(att.contentType) ?? "").startsWith("text/html");
177
+ }
178
+ function extractHtmlFromAttachment(att) {
179
+ if (!isHtmlAttachment(att)) return;
180
+ if (typeof att.content === "string") return att.content;
181
+ if (!isRecord$2(att.content)) return;
182
+ return typeof att.content.text === "string" ? att.content.text : typeof att.content.body === "string" ? att.content.body : typeof att.content.content === "string" ? att.content.content : void 0;
183
+ }
184
+ function canonicalizeInlineBase64Payload(value) {
185
+ let cleaned = "";
186
+ let padding = 0;
187
+ let sawPadding = false;
188
+ for (let index = 0; index < value.length; index += 1) {
189
+ const code = value.charCodeAt(index);
190
+ if (code <= 32) continue;
191
+ if (code === 61) {
192
+ padding += 1;
193
+ if (padding > 2) return;
194
+ sawPadding = true;
195
+ cleaned += "=";
196
+ continue;
197
+ }
198
+ if (sawPadding || !(code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 43 || code === 47)) return;
199
+ cleaned += value[index];
200
+ }
201
+ return cleaned && cleaned.length % 4 === 0 ? cleaned : void 0;
202
+ }
203
+ function decodeDataImageWithLimits(src, opts) {
204
+ const match = /^data:(image\/[a-z0-9.+-]+)?(;base64)?,(.*)$/i.exec(src);
205
+ if (!match) return {
206
+ candidate: null,
207
+ estimatedBytes: 0
208
+ };
209
+ const contentType = normalizeLowercaseStringOrEmpty(match[1] ?? "");
210
+ if (!Boolean(match[2])) return {
211
+ candidate: null,
212
+ estimatedBytes: 0
213
+ };
214
+ const canonicalPayload = canonicalizeInlineBase64Payload(match[3] ?? "");
215
+ if (!canonicalPayload) return {
216
+ candidate: null,
217
+ estimatedBytes: 0
218
+ };
219
+ const estimatedBytes = estimateBase64DecodedBytes(canonicalPayload);
220
+ if (estimatedBytes <= 0) return {
221
+ candidate: null,
222
+ estimatedBytes: 0
223
+ };
224
+ if (typeof opts.maxInlineBytes === "number" && estimatedBytes > opts.maxInlineBytes) return {
225
+ candidate: null,
226
+ estimatedBytes
227
+ };
228
+ try {
229
+ return {
230
+ candidate: {
231
+ kind: "data",
232
+ data: Buffer.from(canonicalPayload, "base64"),
233
+ contentType,
234
+ placeholder: "<media:image>"
235
+ },
236
+ estimatedBytes
237
+ };
238
+ } catch {
239
+ return {
240
+ candidate: null,
241
+ estimatedBytes: 0
242
+ };
243
+ }
244
+ }
245
+ function fileHintFromUrl(src) {
246
+ try {
247
+ return new URL(src).pathname.split("/").pop() || void 0;
248
+ } catch {
249
+ return;
250
+ }
251
+ }
252
+ function extractInlineImageCandidates(attachments, limits) {
253
+ const out = [];
254
+ let totalEstimatedInlineBytes = 0;
255
+ outerLoop: for (const att of attachments) {
256
+ const html = extractHtmlFromAttachment(att);
257
+ if (!html) continue;
258
+ IMG_SRC_RE.lastIndex = 0;
259
+ let match = IMG_SRC_RE.exec(html);
260
+ while (match) {
261
+ const src = match[1]?.trim();
262
+ if (src && !src.startsWith("cid:")) if (src.startsWith("data:")) {
263
+ const { candidate: decoded, estimatedBytes } = decodeDataImageWithLimits(src, { maxInlineBytes: limits?.maxInlineBytes });
264
+ if (decoded) {
265
+ const nextTotal = totalEstimatedInlineBytes + estimatedBytes;
266
+ if (typeof limits?.maxInlineTotalBytes === "number" && nextTotal > limits.maxInlineTotalBytes) break outerLoop;
267
+ totalEstimatedInlineBytes = nextTotal;
268
+ out.push(decoded);
269
+ }
270
+ } else out.push({
271
+ kind: "url",
272
+ url: src,
273
+ fileHint: fileHintFromUrl(src),
274
+ placeholder: "<media:image>"
275
+ });
276
+ match = IMG_SRC_RE.exec(html);
277
+ }
278
+ }
279
+ return out;
280
+ }
281
+ function safeHostForUrl(url) {
282
+ try {
283
+ return normalizeLowercaseStringOrEmpty(new URL(url).hostname);
284
+ } catch {
285
+ return "invalid-url";
286
+ }
287
+ }
288
+ function resolveAllowedHosts(input) {
289
+ return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_HOST_ALLOWLIST);
290
+ }
291
+ function resolveAuthAllowedHosts(input) {
292
+ return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST);
293
+ }
294
+ function resolveAttachmentFetchPolicy(params) {
295
+ return {
296
+ allowHosts: resolveAllowedHosts(params?.allowHosts),
297
+ authAllowHosts: resolveAuthAllowedHosts(params?.authAllowHosts)
298
+ };
299
+ }
300
+ function isUrlAllowed(url, allowlist) {
301
+ return isHttpsUrlAllowedByHostnameSuffixAllowlist(url, allowlist);
302
+ }
303
+ function applyAuthorizationHeaderForUrl(params) {
304
+ if (!params.bearerToken) {
305
+ params.headers.delete("Authorization");
306
+ return;
307
+ }
308
+ if (isUrlAllowed(params.url, params.authAllowHosts)) {
309
+ params.headers.set("Authorization", `Bearer ${params.bearerToken}`);
310
+ return;
311
+ }
312
+ params.headers.delete("Authorization");
313
+ }
314
+ function resolveMediaSsrfPolicy(allowHosts) {
315
+ return buildHostnameAllowlistPolicyFromSuffixAllowlist(allowHosts);
316
+ }
317
+ /**
318
+ * Returns true if the given IPv4 or IPv6 address is in a private, loopback,
319
+ * or link-local range that must never be reached from media downloads.
320
+ *
321
+ * Delegates to the SDK's `isPrivateIpAddress` which handles IPv4-mapped IPv6,
322
+ * expanded notation, NAT64, 6to4, Teredo, octal IPv4, and fails closed on
323
+ * parse errors.
324
+ */
325
+ const isPrivateOrReservedIP = isPrivateIpAddress;
326
+ /**
327
+ * Resolve a hostname via DNS and reject private/reserved IPs.
328
+ * Throws if the resolved IP is private or resolution fails.
329
+ */
330
+ async function resolveAndValidateIP(hostname, resolveFn) {
331
+ const resolve = resolveFn ?? lookup;
332
+ let resolved;
333
+ try {
334
+ resolved = await resolve(hostname);
335
+ } catch {
336
+ throw new Error(`DNS resolution failed for "${hostname}"`);
337
+ }
338
+ if (isPrivateOrReservedIP(resolved.address)) throw new Error(`Hostname "${hostname}" resolves to private/reserved IP (${resolved.address})`);
339
+ return resolved.address;
340
+ }
341
+ /** Maximum number of redirects to follow in safeFetch. */
342
+ const MAX_SAFE_REDIRECTS = 5;
343
+ /**
344
+ * Fetch a URL with redirect: "manual", validating each redirect target
345
+ * against the hostname allowlist and optional DNS-resolved IP (anti-SSRF).
346
+ *
347
+ * This prevents:
348
+ * - Auto-following redirects to non-allowlisted hosts
349
+ * - DNS rebinding attacks when a lookup function is provided
350
+ */
351
+ async function safeFetch(params) {
352
+ const fetchFn = params.fetchFn ?? fetch;
353
+ const resolveFn = params.resolveFn ?? lookup;
354
+ const hasDispatcher = Boolean(params.requestInit && typeof params.requestInit === "object" && "dispatcher" in params.requestInit);
355
+ const currentHeaders = new Headers(params.requestInit?.headers);
356
+ let currentUrl = params.url;
357
+ if (!isUrlAllowed(currentUrl, params.allowHosts)) throw new Error(`Initial download URL blocked: ${currentUrl}`);
358
+ if (resolveFn) try {
359
+ const initialHost = new URL(currentUrl).hostname;
360
+ await resolveAndValidateIP(initialHost, resolveFn);
361
+ } catch {
362
+ throw new Error(`Initial download URL blocked: ${currentUrl}`);
363
+ }
364
+ for (let i = 0; i <= MAX_SAFE_REDIRECTS; i++) {
365
+ const res = await fetchFn(currentUrl, {
366
+ ...params.requestInit,
367
+ headers: currentHeaders,
368
+ redirect: "manual"
369
+ });
370
+ if (![
371
+ 301,
372
+ 302,
373
+ 303,
374
+ 307,
375
+ 308
376
+ ].includes(res.status)) return res;
377
+ const location = res.headers.get("location");
378
+ if (!location) return res;
379
+ let redirectUrl;
380
+ try {
381
+ redirectUrl = new URL(location, currentUrl).toString();
382
+ } catch {
383
+ throw new Error(`Invalid redirect URL: ${location}`);
384
+ }
385
+ if (!isUrlAllowed(redirectUrl, params.allowHosts)) throw new Error(`Media redirect target blocked by allowlist: ${redirectUrl}`);
386
+ if (currentHeaders.has("authorization") && params.authorizationAllowHosts && !isUrlAllowed(redirectUrl, params.authorizationAllowHosts)) currentHeaders.delete("authorization");
387
+ if (hasDispatcher) return res;
388
+ if (resolveFn) {
389
+ const redirectHost = new URL(redirectUrl).hostname;
390
+ await resolveAndValidateIP(redirectHost, resolveFn);
391
+ }
392
+ currentUrl = redirectUrl;
393
+ }
394
+ throw new Error(`Too many redirects (>${MAX_SAFE_REDIRECTS})`);
395
+ }
396
+ async function safeFetchWithPolicy(params) {
397
+ return await safeFetch({
398
+ url: params.url,
399
+ allowHosts: params.policy.allowHosts,
400
+ authorizationAllowHosts: params.policy.authAllowHosts,
401
+ fetchFn: params.fetchFn,
402
+ requestInit: params.requestInit,
403
+ resolveFn: params.resolveFn
404
+ });
405
+ }
406
+ //#endregion
407
+ //#region extensions/msteams/src/errors.ts
408
+ function isRecord$1(value) {
409
+ return typeof value === "object" && value !== null && !Array.isArray(value);
410
+ }
411
+ function formatUnknownError(err) {
412
+ if (err instanceof Error) return err.message;
413
+ if (typeof err === "string") return err;
414
+ if (err === null) return "null";
415
+ if (err === void 0) return "undefined";
416
+ if (typeof err === "number" || typeof err === "boolean" || typeof err === "bigint") return String(err);
417
+ if (typeof err === "symbol") return err.description ?? err.toString();
418
+ if (typeof err === "function") return err.name ? `[function ${err.name}]` : "[function]";
419
+ try {
420
+ return JSON.stringify(err) ?? "unknown error";
421
+ } catch {
422
+ return "unknown error";
423
+ }
424
+ }
425
+ function extractStatusCode(err) {
426
+ if (!isRecord$1(err)) return null;
427
+ const direct = err.statusCode ?? err.status;
428
+ if (typeof direct === "number" && Number.isFinite(direct)) return direct;
429
+ if (typeof direct === "string") {
430
+ const parsed = Number.parseInt(direct, 10);
431
+ if (Number.isFinite(parsed)) return parsed;
432
+ }
433
+ const response = err.response;
434
+ if (isRecord$1(response)) {
435
+ const status = response.status;
436
+ if (typeof status === "number" && Number.isFinite(status)) return status;
437
+ if (typeof status === "string") {
438
+ const parsed = Number.parseInt(status, 10);
439
+ if (Number.isFinite(parsed)) return parsed;
440
+ }
441
+ }
442
+ return null;
443
+ }
444
+ function extractErrorCode(err) {
445
+ if (!isRecord$1(err)) return null;
446
+ const direct = err.code;
447
+ if (typeof direct === "string" && direct.trim()) return direct;
448
+ const response = err.response;
449
+ if (!isRecord$1(response)) return null;
450
+ const body = response.body;
451
+ if (isRecord$1(body)) {
452
+ const error = body.error;
453
+ if (isRecord$1(error) && typeof error.code === "string" && error.code.trim()) return error.code;
454
+ }
455
+ return null;
456
+ }
457
+ function extractRetryAfterMs(err) {
458
+ if (!isRecord$1(err)) return null;
459
+ const direct = err.retryAfterMs ?? err.retry_after_ms;
460
+ if (typeof direct === "number" && Number.isFinite(direct) && direct >= 0) return direct;
461
+ const retryAfter = err.retryAfter ?? err.retry_after;
462
+ if (typeof retryAfter === "number" && Number.isFinite(retryAfter)) return retryAfter >= 0 ? retryAfter * 1e3 : null;
463
+ if (typeof retryAfter === "string") {
464
+ const parsed = Number.parseFloat(retryAfter);
465
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1e3;
466
+ }
467
+ const response = err.response;
468
+ if (!isRecord$1(response)) return null;
469
+ const headers = response.headers;
470
+ if (!headers) return null;
471
+ if (isRecord$1(headers)) {
472
+ const raw = headers["retry-after"] ?? headers["Retry-After"];
473
+ if (typeof raw === "string") {
474
+ const parsed = Number.parseFloat(raw);
475
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1e3;
476
+ }
477
+ }
478
+ if (typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function") {
479
+ const raw = headers.get("retry-after");
480
+ if (raw) {
481
+ const parsed = Number.parseFloat(raw);
482
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1e3;
483
+ }
484
+ }
485
+ return null;
486
+ }
487
+ /**
488
+ * Classify outbound send errors for safe retries and actionable logs.
489
+ *
490
+ * Important: We only mark errors as retryable when we have an explicit HTTP
491
+ * status code that indicates the message was not accepted (e.g. 429, 5xx).
492
+ * For transport-level errors where delivery is ambiguous, we prefer to avoid
493
+ * retries to reduce the chance of duplicate posts.
494
+ */
495
+ function classifyMSTeamsSendError(err) {
496
+ const statusCode = extractStatusCode(err);
497
+ const retryAfterMs = extractRetryAfterMs(err);
498
+ const errorCode = extractErrorCode(err) ?? void 0;
499
+ if (statusCode === 401) return {
500
+ kind: "auth",
501
+ statusCode,
502
+ errorCode
503
+ };
504
+ if (statusCode === 403) {
505
+ if (errorCode === "ContentStreamNotAllowed") return {
506
+ kind: "permanent",
507
+ statusCode,
508
+ errorCode
509
+ };
510
+ return {
511
+ kind: "auth",
512
+ statusCode,
513
+ errorCode
514
+ };
515
+ }
516
+ if (statusCode === 429) return {
517
+ kind: "throttled",
518
+ statusCode,
519
+ retryAfterMs: retryAfterMs ?? void 0,
520
+ errorCode
521
+ };
522
+ if (statusCode === 408 || statusCode != null && statusCode >= 500) return {
523
+ kind: "transient",
524
+ statusCode,
525
+ retryAfterMs: retryAfterMs ?? void 0,
526
+ errorCode
527
+ };
528
+ if (statusCode != null && statusCode >= 400) return {
529
+ kind: "permanent",
530
+ statusCode,
531
+ errorCode
532
+ };
533
+ if (statusCode == null) {
534
+ const networkCode = isRecord$1(err) && typeof err.code === "string" ? err.code : null;
535
+ if (networkCode === "ECONNREFUSED" || networkCode === "ENOTFOUND" || networkCode === "EHOSTUNREACH" || networkCode === "ETIMEDOUT" || networkCode === "ECONNRESET") return {
536
+ kind: "network",
537
+ errorCode: networkCode
538
+ };
539
+ }
540
+ return {
541
+ kind: "unknown",
542
+ statusCode: statusCode ?? void 0,
543
+ retryAfterMs: retryAfterMs ?? void 0,
544
+ errorCode
545
+ };
546
+ }
547
+ /**
548
+ * Detect whether an error is caused by a revoked Proxy.
549
+ *
550
+ * The Bot Framework SDK wraps TurnContext in a Proxy that is revoked once the
551
+ * turn handler returns. Any later access (e.g. from a debounced callback)
552
+ * throws a TypeError whose message contains the distinctive "proxy that has
553
+ * been revoked" string.
554
+ */
555
+ function isRevokedProxyError(err) {
556
+ if (!(err instanceof TypeError)) return false;
557
+ return /proxy that has been revoked/i.test(err.message);
558
+ }
559
+ function formatMSTeamsSendErrorHint(classification) {
560
+ if (classification.kind === "auth") return "check msteams appId/appPassword/tenantId (or env vars MSTEAMS_APP_ID/MSTEAMS_APP_PASSWORD/MSTEAMS_TENANT_ID)";
561
+ if (classification.errorCode === "ContentStreamNotAllowed") return "Teams expired the content stream; stop streaming earlier and fall back to normal message delivery";
562
+ if (classification.kind === "throttled") return "Teams throttled the bot; backing off may help";
563
+ if (classification.kind === "transient") return "transient Teams/Bot Framework error; retry may succeed";
564
+ if (classification.kind === "network") return "transport-level failure sending reply to Teams Bot Connector (smba.trafficmanager.net) — check egress firewall rules allow outbound HTTPS to smba.trafficmanager.net";
565
+ }
566
+ //#endregion
567
+ //#region extensions/msteams/src/user-agent.ts
568
+ let cachedUserAgent;
569
+ function resolveTeamsSdkVersion() {
570
+ try {
571
+ return createRequire(import.meta.url)("@microsoft/teams.apps/package.json").version ?? "unknown";
572
+ } catch {
573
+ return "unknown";
574
+ }
575
+ }
576
+ function resolveKlawVersion() {
577
+ try {
578
+ return getMSTeamsRuntime().version;
579
+ } catch {
580
+ return "unknown";
581
+ }
582
+ }
583
+ function buildUserAgent() {
584
+ if (cachedUserAgent) return cachedUserAgent;
585
+ cachedUserAgent = `teams.ts[apps]/${resolveTeamsSdkVersion()} Klaw/${resolveKlawVersion()}`;
586
+ return cachedUserAgent;
587
+ }
588
+ function ensureUserAgentHeader(headers) {
589
+ const nextHeaders = new Headers(headers);
590
+ if (!nextHeaders.has("User-Agent")) nextHeaders.set("User-Agent", buildUserAgent());
591
+ return nextHeaders;
592
+ }
593
+ //#endregion
594
+ //#region extensions/msteams/src/sdk.ts
595
+ const AZURE_IDENTITY_MODULE = "@azure/identity";
596
+ let azureIdentityModulePromise = null;
597
+ async function loadAzureIdentity() {
598
+ azureIdentityModulePromise ??= import(AZURE_IDENTITY_MODULE);
599
+ return azureIdentityModulePromise;
600
+ }
601
+ let msTeamsSdkPromise = null;
602
+ async function loadMSTeamsSdk() {
603
+ msTeamsSdkPromise ??= Promise.all([import("@microsoft/teams.apps"), import("@microsoft/teams.api")]).then(([appsModule, apiModule]) => ({
604
+ App: appsModule.App,
605
+ Client: apiModule.Client
606
+ }));
607
+ return msTeamsSdkPromise;
608
+ }
609
+ /**
610
+ * Create a no-op HTTP server adapter that satisfies the Teams SDK's
611
+ * IHttpServerAdapter interface without spinning up an Express server.
612
+ *
613
+ * Klaw manages its own Express server for the Teams webhook endpoint, so
614
+ * the SDK's built-in HTTP server is unnecessary. Passing this adapter via the
615
+ * `httpServerAdapter` option prevents the SDK from creating the default
616
+ * HttpPlugin (which uses the deprecated `plugins` array and registers an
617
+ * Express middleware with the pattern `/api*` — invalid in Express 5).
618
+ *
619
+ * See: https://github.com/klaw/klaw/issues/55161
620
+ * See: https://github.com/klaw/klaw/issues/60732
621
+ */
622
+ function createNoOpHttpServerAdapter() {
623
+ return { registerRoute() {} };
624
+ }
625
+ /**
626
+ * Create a Teams SDK App instance from credentials. The App manages token
627
+ * acquisition, JWT validation, and the HTTP server lifecycle.
628
+ *
629
+ * This replaces the previous CloudAdapter + MsalTokenProvider + authorizeJWT
630
+ * from @microsoft/agents-hosting.
631
+ */
632
+ async function createMSTeamsApp(creds, sdk) {
633
+ if (creds.type === "federated") return createFederatedApp(creds, sdk);
634
+ return new sdk.App({
635
+ clientId: creds.appId,
636
+ clientSecret: creds.appPassword,
637
+ tenantId: creds.tenantId,
638
+ httpServerAdapter: createNoOpHttpServerAdapter()
639
+ });
640
+ }
641
+ function createFederatedApp(creds, sdk) {
642
+ if (creds.useManagedIdentity) return createManagedIdentityApp(creds, sdk);
643
+ if (!creds.certificatePath) throw new Error("Federated credentials require either a certificate path or managed identity.");
644
+ let privateKey;
645
+ try {
646
+ privateKey = fs.readFileSync(creds.certificatePath, "utf-8");
647
+ } catch (err) {
648
+ const msg = err instanceof Error ? err.message : String(err);
649
+ throw new Error(`Failed to read certificate file at '${creds.certificatePath}': ${msg}`, { cause: err });
650
+ }
651
+ return createCertificateApp(creds, privateKey, sdk);
652
+ }
653
+ function createCertificateApp(creds, privateKey, sdk) {
654
+ let credentialPromise = null;
655
+ const getCredential = async () => {
656
+ if (!credentialPromise) credentialPromise = loadAzureIdentity().then((az) => new az.ClientCertificateCredential(creds.tenantId, creds.appId, { certificate: privateKey }));
657
+ return credentialPromise;
658
+ };
659
+ const tokenProvider = async (scope) => {
660
+ const token = await (await getCredential()).getToken(scope);
661
+ if (!token?.token) throw new Error("Failed to acquire token via certificate credential.");
662
+ return token.token;
663
+ };
664
+ return new sdk.App({
665
+ clientId: creds.appId,
666
+ tenantId: creds.tenantId,
667
+ token: tokenProvider,
668
+ httpServerAdapter: createNoOpHttpServerAdapter()
669
+ });
670
+ }
671
+ function createManagedIdentityApp(creds, sdk) {
672
+ let credentialPromise = null;
673
+ const getCredential = async () => {
674
+ if (!credentialPromise) credentialPromise = loadAzureIdentity().then((az) => creds.managedIdentityClientId ? new az.ManagedIdentityCredential(creds.managedIdentityClientId) : new az.ManagedIdentityCredential());
675
+ return credentialPromise;
676
+ };
677
+ const tokenProvider = async (scope) => {
678
+ const token = await (await getCredential()).getToken(scope);
679
+ if (!token?.token) throw new Error("Failed to acquire token via managed identity.");
680
+ return token.token;
681
+ };
682
+ return new sdk.App({
683
+ clientId: creds.appId,
684
+ tenantId: creds.tenantId,
685
+ token: tokenProvider,
686
+ httpServerAdapter: createNoOpHttpServerAdapter()
687
+ });
688
+ }
689
+ /**
690
+ * Build a token provider that uses the Teams SDK App for token acquisition.
691
+ */
692
+ function createMSTeamsTokenProvider(app) {
693
+ return { async getAccessToken(scope) {
694
+ if (scope.includes("graph.microsoft.com")) {
695
+ const token = await app.getAppGraphToken();
696
+ return token ? String(token) : "";
697
+ }
698
+ const token = await app.getBotToken();
699
+ return token ? String(token) : "";
700
+ } };
701
+ }
702
+ function createBotTokenGetter(app) {
703
+ return async () => {
704
+ const token = await app.getBotToken();
705
+ return token ? String(token) : void 0;
706
+ };
707
+ }
708
+ function createApiClient(sdk, serviceUrl, getToken) {
709
+ return new sdk.Client(serviceUrl, {
710
+ token: async () => await getToken() || void 0,
711
+ headers: { "User-Agent": buildUserAgent() }
712
+ });
713
+ }
714
+ function normalizeOutboundActivity(textOrActivity) {
715
+ return typeof textOrActivity === "string" ? {
716
+ type: "message",
717
+ text: textOrActivity
718
+ } : textOrActivity;
719
+ }
720
+ function createSendContext(params) {
721
+ const apiClient = params.serviceUrl && params.conversationId ? createApiClient(params.sdk, params.serviceUrl, params.getToken) : void 0;
722
+ return {
723
+ async sendActivity(textOrActivity) {
724
+ const msg = normalizeOutboundActivity(textOrActivity);
725
+ if (params.treatInvokeResponseAsNoop && msg.type === "invokeResponse") return { id: "invokeResponse" };
726
+ if (!apiClient || !params.conversationId) return { id: "unknown" };
727
+ const existingChannelData = msg.channelData && typeof msg.channelData === "object" ? msg.channelData : void 0;
728
+ const channelData = params.tenantId ? {
729
+ ...existingChannelData,
730
+ tenant: { id: params.tenantId }
731
+ } : existingChannelData;
732
+ return await apiClient.conversations.activities(params.conversationId).create({
733
+ type: "message",
734
+ ...msg,
735
+ ...channelData ? { channelData } : {},
736
+ from: params.bot?.id ? {
737
+ id: params.bot.id,
738
+ name: params.bot.name ?? "",
739
+ role: "bot"
740
+ } : void 0,
741
+ conversation: {
742
+ id: params.conversationId,
743
+ conversationType: params.conversationType ?? "personal",
744
+ ...params.tenantId ? { tenantId: params.tenantId } : {}
745
+ },
746
+ ...params.recipientId || params.recipientAadObjectId ? { recipient: {
747
+ ...params.recipientId ? { id: params.recipientId } : {},
748
+ ...params.recipientAadObjectId ? { aadObjectId: params.recipientAadObjectId } : {}
749
+ } } : {},
750
+ ...params.replyToActivityId && !msg.replyToId ? { replyToId: params.replyToActivityId } : {}
751
+ });
752
+ },
753
+ async updateActivity(activityUpdate) {
754
+ const nextActivity = activityUpdate;
755
+ const activityId = nextActivity.id;
756
+ if (!activityId) throw new Error("updateActivity requires an activity id");
757
+ if (!params.serviceUrl || !params.conversationId) return { id: "unknown" };
758
+ return await updateActivityViaRest({
759
+ serviceUrl: params.serviceUrl,
760
+ conversationId: params.conversationId,
761
+ activityId,
762
+ activity: nextActivity,
763
+ token: await params.getToken()
764
+ });
765
+ },
766
+ async deleteActivity(activityId) {
767
+ if (!activityId) throw new Error("deleteActivity requires an activity id");
768
+ if (!params.serviceUrl || !params.conversationId) return;
769
+ await deleteActivityViaRest({
770
+ serviceUrl: params.serviceUrl,
771
+ conversationId: params.conversationId,
772
+ activityId,
773
+ token: await params.getToken()
774
+ });
775
+ }
776
+ };
777
+ }
778
+ function createProcessContext(params) {
779
+ const serviceUrl = params.activity?.serviceUrl;
780
+ const conversationId = (params.activity?.conversation)?.id;
781
+ const conversationType = (params.activity?.conversation)?.conversationType;
782
+ const replyToActivityId = params.activity?.id;
783
+ const bot = params.activity?.recipient && typeof params.activity.recipient === "object" ? {
784
+ id: params.activity.recipient.id,
785
+ name: params.activity.recipient.name
786
+ } : void 0;
787
+ const sendContext = createSendContext({
788
+ sdk: params.sdk,
789
+ serviceUrl,
790
+ conversationId,
791
+ conversationType,
792
+ bot,
793
+ replyToActivityId,
794
+ getToken: params.getToken,
795
+ treatInvokeResponseAsNoop: true
796
+ });
797
+ return {
798
+ activity: params.activity,
799
+ ...sendContext,
800
+ async sendActivities(activities) {
801
+ const results = [];
802
+ for (const activity of activities) results.push(await sendContext.sendActivity(activity));
803
+ return results;
804
+ }
805
+ };
806
+ }
807
+ /**
808
+ * Update an existing activity via the Bot Framework REST API.
809
+ * PUT /v3/conversations/{conversationId}/activities/{activityId}
810
+ */
811
+ async function updateActivityViaRest(params) {
812
+ const { serviceUrl, conversationId, activityId, activity, token } = params;
813
+ const url = `${serviceUrl.replace(/\/+$/, "")}/v3/conversations/${encodeURIComponent(conversationId)}/activities/${encodeURIComponent(activityId)}`;
814
+ const headers = {
815
+ "Content-Type": "application/json",
816
+ "User-Agent": buildUserAgent()
817
+ };
818
+ if (token) headers.Authorization = `Bearer ${token}`;
819
+ const currentFetch = globalThis.fetch;
820
+ const { response, release } = await fetchWithSsrFGuard({
821
+ url,
822
+ fetchImpl: async (input, guardedInit) => await currentFetch(input, guardedInit),
823
+ init: {
824
+ method: "PUT",
825
+ headers,
826
+ body: JSON.stringify({
827
+ type: "message",
828
+ ...activity,
829
+ id: activityId
830
+ })
831
+ },
832
+ auditContext: "msteams-update-activity"
833
+ });
834
+ try {
835
+ if (!response.ok) {
836
+ const body = await response.text().catch(() => "");
837
+ throw Object.assign(/* @__PURE__ */ new Error(`updateActivity failed: HTTP ${response.status} ${body}`), { statusCode: response.status });
838
+ }
839
+ return await response.json().catch(() => ({ id: activityId }));
840
+ } finally {
841
+ await release();
842
+ }
843
+ }
844
+ /**
845
+ * Delete an existing activity via the Bot Framework REST API.
846
+ * DELETE /v3/conversations/{conversationId}/activities/{activityId}
847
+ */
848
+ async function deleteActivityViaRest(params) {
849
+ const { serviceUrl, conversationId, activityId, token } = params;
850
+ const url = `${serviceUrl.replace(/\/+$/, "")}/v3/conversations/${encodeURIComponent(conversationId)}/activities/${encodeURIComponent(activityId)}`;
851
+ const headers = { "User-Agent": buildUserAgent() };
852
+ if (token) headers.Authorization = `Bearer ${token}`;
853
+ const currentFetch = globalThis.fetch;
854
+ const { response, release } = await fetchWithSsrFGuard({
855
+ url,
856
+ fetchImpl: async (input, guardedInit) => await currentFetch(input, guardedInit),
857
+ init: {
858
+ method: "DELETE",
859
+ headers
860
+ },
861
+ auditContext: "msteams-delete-activity"
862
+ });
863
+ try {
864
+ if (!response.ok) {
865
+ const body = await response.text().catch(() => "");
866
+ throw Object.assign(/* @__PURE__ */ new Error(`deleteActivity failed: HTTP ${response.status} ${body}`), { statusCode: response.status });
867
+ }
868
+ } finally {
869
+ await release();
870
+ }
871
+ }
872
+ /**
873
+ * Build a CloudAdapter-compatible adapter using the Teams SDK REST client.
874
+ *
875
+ * This replaces the previous CloudAdapter from @microsoft/agents-hosting.
876
+ * For incoming requests: the App's HTTP server handles JWT validation.
877
+ * For proactive sends: uses the Bot Framework REST API via
878
+ * @microsoft/teams.api Client.
879
+ */
880
+ function createMSTeamsAdapter(app, sdk) {
881
+ return {
882
+ async continueConversation(_appId, reference, logic) {
883
+ const serviceUrl = reference.serviceUrl;
884
+ if (!serviceUrl) throw new Error("Missing serviceUrl in conversation reference");
885
+ const conversationId = reference.conversation?.id;
886
+ if (!conversationId) throw new Error("Missing conversation.id in conversation reference");
887
+ const tenantId = reference.tenantId ?? reference.conversation?.tenantId;
888
+ const recipientAadObjectId = reference.aadObjectId ?? reference.user?.aadObjectId;
889
+ const recipientId = reference.user?.id;
890
+ await logic(createSendContext({
891
+ sdk,
892
+ serviceUrl,
893
+ conversationId,
894
+ conversationType: reference.conversation?.conversationType,
895
+ bot: reference.agent ?? void 0,
896
+ getToken: createBotTokenGetter(app),
897
+ tenantId,
898
+ recipientId,
899
+ recipientAadObjectId
900
+ }));
901
+ },
902
+ async process(req, res, logic) {
903
+ const request = req;
904
+ const response = res;
905
+ const activity = request.body;
906
+ const isInvoke = activity?.type === "invoke";
907
+ try {
908
+ const context = createProcessContext({
909
+ sdk,
910
+ activity,
911
+ getToken: createBotTokenGetter(app)
912
+ });
913
+ if (isInvoke) response.status(200).send();
914
+ await logic(context);
915
+ if (!isInvoke) response.status(200).send();
916
+ } catch (err) {
917
+ if (!isInvoke) response.status(500).send({ error: formatUnknownError(err) });
918
+ }
919
+ },
920
+ async updateActivity(_context, _activity) {},
921
+ async deleteActivity(_context, _reference) {}
922
+ };
923
+ }
924
+ async function loadMSTeamsSdkWithAuth(creds) {
925
+ const sdk = await loadMSTeamsSdk();
926
+ return {
927
+ sdk,
928
+ app: await createMSTeamsApp(creds, sdk)
929
+ };
930
+ }
931
+ /**
932
+ * Bot Framework issuer → JWKS mapping.
933
+ * During Microsoft's transition, inbound service tokens can be signed by either
934
+ * the legacy Bot Framework issuer or the Entra issuer. Each gets its own JWKS
935
+ * endpoint so we verify signatures with the correct key set.
936
+ */
937
+ const BOT_FRAMEWORK_ISSUERS = [
938
+ {
939
+ issuer: "https://api.botframework.com",
940
+ jwksUri: "https://login.botframework.com/v1/.well-known/keys"
941
+ },
942
+ {
943
+ issuer: (tenantId) => `https://login.microsoftonline.com/${tenantId}/v2.0`,
944
+ jwksUri: "https://login.microsoftonline.com/common/discovery/v2.0/keys"
945
+ },
946
+ {
947
+ issuer: (tenantId) => `https://sts.windows.net/${tenantId}/`,
948
+ jwksUri: "https://login.microsoftonline.com/common/discovery/v2.0/keys"
949
+ }
950
+ ];
951
+ const BOT_FRAMEWORK_GLOBAL_AUDIENCE = "https://api.botframework.com";
952
+ function isJwtPayloadObject(value) {
953
+ return !!value && typeof value === "object" && !Array.isArray(value);
954
+ }
955
+ function getAudienceClaims(payload) {
956
+ if (!isJwtPayloadObject(payload)) return [];
957
+ const audience = payload.aud;
958
+ if (typeof audience === "string") {
959
+ const trimmed = audience.trim();
960
+ return trimmed ? [trimmed] : [];
961
+ }
962
+ if (Array.isArray(audience)) return audience.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean);
963
+ return [];
964
+ }
965
+ function normalizeBotIdentityClaim(value) {
966
+ if (typeof value !== "string") return null;
967
+ return value.trim().toLowerCase() || null;
968
+ }
969
+ function hasExpectedBotIdentity(payload, expectedAppId) {
970
+ if (!isJwtPayloadObject(payload)) return false;
971
+ const expected = normalizeBotIdentityClaim(expectedAppId);
972
+ if (!expected) return false;
973
+ return normalizeBotIdentityClaim(payload.appid) === expected || normalizeBotIdentityClaim(payload.azp) === expected;
974
+ }
975
+ let botFrameworkJwtDepsPromise = null;
976
+ function hasDefaultExport(value) {
977
+ return !!value && typeof value === "object" && "default" in value;
978
+ }
979
+ function isJsonwebtokenRuntime(value) {
980
+ return !!value && typeof value === "object" && typeof value.decode === "function" && typeof value.verify === "function";
981
+ }
982
+ function loadJsonwebtokenRuntime(jwtModule) {
983
+ const jwt = hasDefaultExport(jwtModule) ? jwtModule.default ?? jwtModule : jwtModule;
984
+ if (!isJsonwebtokenRuntime(jwt)) throw new Error("jsonwebtoken did not export decode/verify");
985
+ return jwt;
986
+ }
987
+ function isJwksClientRuntime(value) {
988
+ return typeof value === "function";
989
+ }
990
+ function loadJwksClientRuntime(jwksModule) {
991
+ const direct = jwksModule && typeof jwksModule === "object" ? jwksModule.JwksClient : void 0;
992
+ const fallback = hasDefaultExport(jwksModule) && jwksModule.default && typeof jwksModule.default === "object" ? jwksModule.default.JwksClient : void 0;
993
+ const JwksClient = direct ?? fallback;
994
+ if (!isJwksClientRuntime(JwksClient)) throw new Error("jwks-rsa did not export JwksClient");
995
+ return JwksClient;
996
+ }
997
+ async function loadBotFrameworkJwtDeps() {
998
+ botFrameworkJwtDepsPromise ??= Promise.all([import("jsonwebtoken"), import("jwks-rsa")]).then(([jwtModule, jwksModule]) => {
999
+ return {
1000
+ jwt: loadJsonwebtokenRuntime(jwtModule),
1001
+ JwksClient: loadJwksClientRuntime(jwksModule)
1002
+ };
1003
+ });
1004
+ return botFrameworkJwtDepsPromise;
1005
+ }
1006
+ /**
1007
+ * Create a Bot Framework JWT validator using jsonwebtoken + jwks-rsa directly.
1008
+ *
1009
+ * The @microsoft/teams.apps JwtValidator hardcodes audience to [clientId, api://clientId],
1010
+ * which rejects valid Bot Framework tokens that carry aud: "https://api.botframework.com".
1011
+ * This implementation uses jsonwebtoken directly with the correct audience list, matching
1012
+ * the behavior of the legacy @microsoft/agents-hosting authorizeJWT middleware.
1013
+ *
1014
+ * Security invariants:
1015
+ * - signature verification via issuer-specific JWKS endpoints
1016
+ * - audience validation: appId, api://appId, and https://api.botframework.com
1017
+ * - issuer validation: strict allowlist (Bot Framework + tenant-scoped Entra)
1018
+ * - expiration validation with 5-minute clock tolerance
1019
+ */
1020
+ async function createBotFrameworkJwtValidator(creds) {
1021
+ const { jwt, JwksClient } = await loadBotFrameworkJwtDeps();
1022
+ const allowedAudiences = [
1023
+ creds.appId,
1024
+ `api://${creds.appId}`,
1025
+ BOT_FRAMEWORK_GLOBAL_AUDIENCE
1026
+ ];
1027
+ const allowedIssuers = BOT_FRAMEWORK_ISSUERS.map((entry) => typeof entry.issuer === "function" ? entry.issuer(creds.tenantId) : entry.issuer);
1028
+ const jwksClients = /* @__PURE__ */ new Map();
1029
+ function getJwksClient(uri) {
1030
+ let client = jwksClients.get(uri);
1031
+ if (!client) {
1032
+ client = new JwksClient({
1033
+ jwksUri: uri,
1034
+ cache: true,
1035
+ cacheMaxAge: 6e5,
1036
+ rateLimit: true
1037
+ });
1038
+ jwksClients.set(uri, client);
1039
+ }
1040
+ return client;
1041
+ }
1042
+ /** Decode the token header without verification to determine the kid. */
1043
+ function decodeHeader(token) {
1044
+ const decoded = jwt.decode(token, { complete: true });
1045
+ return decoded && typeof decoded === "object" ? decoded.header : null;
1046
+ }
1047
+ /** Resolve the issuer entry for a token's issuer claim (pre-verification). */
1048
+ function resolveIssuerEntry(issuerClaim) {
1049
+ if (!issuerClaim) return;
1050
+ return BOT_FRAMEWORK_ISSUERS.find((entry) => {
1051
+ return (typeof entry.issuer === "function" ? entry.issuer(creds.tenantId) : entry.issuer) === issuerClaim;
1052
+ });
1053
+ }
1054
+ return { async validate(authHeader, _serviceUrl) {
1055
+ const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
1056
+ if (!token) return false;
1057
+ const header = decodeHeader(token);
1058
+ const unverifiedPayload = jwt.decode(token);
1059
+ if (!header?.kid || !isJwtPayloadObject(unverifiedPayload) || typeof unverifiedPayload.iss !== "string") return false;
1060
+ const issuerEntry = resolveIssuerEntry(unverifiedPayload.iss);
1061
+ if (!issuerEntry) return false;
1062
+ const client = getJwksClient(issuerEntry.jwksUri);
1063
+ try {
1064
+ const publicKey = (await client.getSigningKey(header.kid)).getPublicKey();
1065
+ const verifiedPayload = jwt.verify(token, publicKey, {
1066
+ audience: allowedAudiences,
1067
+ issuer: allowedIssuers,
1068
+ algorithms: ["RS256"],
1069
+ clockTolerance: 300
1070
+ });
1071
+ if (!isJwtPayloadObject(verifiedPayload)) return false;
1072
+ if (getAudienceClaims(verifiedPayload).includes(BOT_FRAMEWORK_GLOBAL_AUDIENCE) && !hasExpectedBotIdentity(verifiedPayload, creds.appId)) return false;
1073
+ return true;
1074
+ } catch (err) {
1075
+ if (isJwksNetworkError(err)) throw err;
1076
+ return false;
1077
+ }
1078
+ } };
1079
+ }
1080
+ /**
1081
+ * Return true when the error originated from a network-level failure fetching
1082
+ * the JWKS endpoint (DNS resolution, connection refused, TLS handshake, etc.)
1083
+ * rather than from token verification logic.
1084
+ */
1085
+ function isJwksNetworkError(err) {
1086
+ if (!(err instanceof Error)) return false;
1087
+ const code = err.code;
1088
+ if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EHOSTUNREACH" || code === "ETIMEDOUT" || code === "ECONNRESET") return true;
1089
+ return /jwks|key fetch|getSigningKey/i.test(err.message) && /network|fetch|connect/i.test(err.message);
1090
+ }
1091
+ //#endregion
1092
+ //#region extensions/msteams/src/token-response.ts
1093
+ function readAccessToken(value) {
1094
+ if (typeof value === "string") return value;
1095
+ if (value && typeof value === "object") {
1096
+ const token = value.accessToken ?? value.token;
1097
+ return typeof token === "string" ? token : null;
1098
+ }
1099
+ return null;
1100
+ }
1101
+ //#endregion
1102
+ //#region extensions/msteams/src/storage.ts
1103
+ function resolveMSTeamsStorePath(params) {
1104
+ if (params.storePath) return params.storePath;
1105
+ if (params.stateDir) return path.join(params.stateDir, params.filename);
1106
+ const env = params.env ?? process.env;
1107
+ const stateDir = params.homedir ? getMSTeamsRuntime().state.resolveStateDir(env, params.homedir) : getMSTeamsRuntime().state.resolveStateDir(env);
1108
+ return path.join(stateDir, params.filename);
1109
+ }
1110
+ //#endregion
1111
+ //#region extensions/msteams/src/token.ts
1112
+ function resolveAuthType(cfg) {
1113
+ const fromCfg = cfg?.authType;
1114
+ if (fromCfg === "secret" || fromCfg === "federated") return fromCfg;
1115
+ if (process.env.MSTEAMS_AUTH_TYPE === "federated") return "federated";
1116
+ return "secret";
1117
+ }
1118
+ function hasConfiguredMSTeamsCredentials(cfg) {
1119
+ const authType = resolveAuthType(cfg);
1120
+ const hasAppId = Boolean(normalizeSecretInputString(cfg?.appId) || normalizeSecretInputString(process.env.MSTEAMS_APP_ID));
1121
+ const hasTenantId = Boolean(normalizeSecretInputString(cfg?.tenantId) || normalizeSecretInputString(process.env.MSTEAMS_TENANT_ID));
1122
+ if (authType === "federated") {
1123
+ const hasCert = Boolean(cfg?.certificatePath || process.env.MSTEAMS_CERTIFICATE_PATH);
1124
+ const hasManagedIdentity = cfg?.useManagedIdentity ?? process.env.MSTEAMS_USE_MANAGED_IDENTITY === "true";
1125
+ return hasAppId && hasTenantId && (hasCert || hasManagedIdentity);
1126
+ }
1127
+ return Boolean(normalizeSecretInputString(cfg?.appId) && hasConfiguredSecretInput(cfg?.appPassword) && normalizeSecretInputString(cfg?.tenantId));
1128
+ }
1129
+ function resolveMSTeamsCredentials(cfg) {
1130
+ const authType = resolveAuthType(cfg);
1131
+ const appId = normalizeSecretInputString(cfg?.appId) || normalizeSecretInputString(process.env.MSTEAMS_APP_ID);
1132
+ const tenantId = normalizeSecretInputString(cfg?.tenantId) || normalizeSecretInputString(process.env.MSTEAMS_TENANT_ID);
1133
+ if (!appId || !tenantId) return;
1134
+ if (authType === "federated") {
1135
+ const certificatePath = cfg?.certificatePath || process.env.MSTEAMS_CERTIFICATE_PATH || void 0;
1136
+ const certificateThumbprint = cfg?.certificateThumbprint || process.env.MSTEAMS_CERTIFICATE_THUMBPRINT || void 0;
1137
+ const useManagedIdentity = cfg?.useManagedIdentity ?? process.env.MSTEAMS_USE_MANAGED_IDENTITY === "true";
1138
+ const managedIdentityClientId = cfg?.managedIdentityClientId || process.env.MSTEAMS_MANAGED_IDENTITY_CLIENT_ID || void 0;
1139
+ if (!certificatePath && !useManagedIdentity) return;
1140
+ return {
1141
+ type: "federated",
1142
+ appId,
1143
+ tenantId,
1144
+ certificatePath,
1145
+ certificateThumbprint,
1146
+ useManagedIdentity: useManagedIdentity || void 0,
1147
+ managedIdentityClientId
1148
+ };
1149
+ }
1150
+ const appPassword = normalizeResolvedSecretInputString({
1151
+ value: cfg?.appPassword,
1152
+ path: "channels.msteams.appPassword"
1153
+ }) || normalizeSecretInputString(process.env.MSTEAMS_APP_PASSWORD);
1154
+ if (!appPassword) return;
1155
+ return {
1156
+ type: "secret",
1157
+ appId,
1158
+ appPassword,
1159
+ tenantId
1160
+ };
1161
+ }
1162
+ const DELEGATED_TOKEN_FILENAME = "msteams-delegated.json";
1163
+ function resolveDelegatedTokenPath() {
1164
+ return resolveMSTeamsStorePath({ filename: DELEGATED_TOKEN_FILENAME });
1165
+ }
1166
+ function loadDelegatedTokens() {
1167
+ try {
1168
+ const content = readFileSync(resolveDelegatedTokenPath(), "utf8");
1169
+ return JSON.parse(content);
1170
+ } catch {
1171
+ return;
1172
+ }
1173
+ }
1174
+ function saveDelegatedTokens(tokens) {
1175
+ const tokenPath = resolveDelegatedTokenPath();
1176
+ privateFileStoreSync(dirname(tokenPath)).writeJson(basename(tokenPath), tokens);
1177
+ }
1178
+ async function resolveDelegatedAccessToken(params) {
1179
+ const tokens = loadDelegatedTokens();
1180
+ if (!tokens) return;
1181
+ if (tokens.expiresAt > Date.now()) return tokens.accessToken;
1182
+ try {
1183
+ const refreshed = await refreshMSTeamsDelegatedTokens({
1184
+ tenantId: params.tenantId,
1185
+ clientId: params.clientId,
1186
+ clientSecret: params.clientSecret,
1187
+ refreshToken: tokens.refreshToken,
1188
+ scopes: tokens.scopes
1189
+ });
1190
+ saveDelegatedTokens(refreshed);
1191
+ return refreshed.accessToken;
1192
+ } catch {
1193
+ return;
1194
+ }
1195
+ }
1196
+ //#endregion
1197
+ //#region extensions/msteams/src/graph.ts
1198
+ const GRAPH_BETA = "https://graph.microsoft.com/beta";
1199
+ const NULL_BODY_STATUSES = new Set([
1200
+ 101,
1201
+ 204,
1202
+ 205,
1203
+ 304
1204
+ ]);
1205
+ function normalizeQuery(value) {
1206
+ return value?.trim() ?? "";
1207
+ }
1208
+ function escapeOData(value) {
1209
+ return value.replace(/'/g, "''");
1210
+ }
1211
+ async function requestGraph(params) {
1212
+ const hasBody = params.body !== void 0;
1213
+ const url = `${params.root ?? "https://graph.microsoft.com/v1.0"}${params.path}`;
1214
+ const currentFetch = globalThis.fetch;
1215
+ const { response, release } = await fetchWithSsrFGuard$1({
1216
+ url,
1217
+ fetchImpl: async (input, guardedInit) => await currentFetch(input, guardedInit),
1218
+ init: {
1219
+ method: params.method,
1220
+ headers: {
1221
+ "User-Agent": buildUserAgent(),
1222
+ Authorization: `Bearer ${params.token}`,
1223
+ ...hasBody ? { "Content-Type": "application/json" } : {},
1224
+ ...params.headers
1225
+ },
1226
+ body: hasBody ? JSON.stringify(params.body) : void 0
1227
+ },
1228
+ auditContext: "msteams.graph"
1229
+ });
1230
+ try {
1231
+ if (!response.ok) {
1232
+ const text = await response.text().catch(() => "");
1233
+ throw new Error(`${params.errorPrefix ?? "Graph"} ${params.path} failed (${response.status}): ${text || "unknown error"}`);
1234
+ }
1235
+ const body = NULL_BODY_STATUSES.has(response.status) ? null : await response.arrayBuffer();
1236
+ return new Response(body, {
1237
+ status: response.status,
1238
+ statusText: response.statusText,
1239
+ headers: new Headers(response.headers)
1240
+ });
1241
+ } finally {
1242
+ await release();
1243
+ }
1244
+ }
1245
+ async function readOptionalGraphJson(res, label) {
1246
+ if (res.status === 204 || res.headers?.get?.("content-length") === "0") return;
1247
+ return await readProviderJsonResponse(res, label);
1248
+ }
1249
+ async function fetchGraphJson(params) {
1250
+ return await readOptionalGraphJson(await requestGraph({
1251
+ token: params.token,
1252
+ path: params.path,
1253
+ method: params.method,
1254
+ body: params.body,
1255
+ headers: params.headers
1256
+ }), `Graph ${params.path} failed`);
1257
+ }
1258
+ /**
1259
+ * Fetch JSON from an absolute Graph API URL (for example @odata.nextLink
1260
+ * pagination URLs) without prepending GRAPH_ROOT.
1261
+ */
1262
+ async function fetchGraphAbsoluteUrl(params) {
1263
+ const { response, release } = await fetchWithSsrFGuard$1({
1264
+ url: params.url,
1265
+ init: { headers: {
1266
+ "User-Agent": buildUserAgent(),
1267
+ Authorization: `Bearer ${params.token}`,
1268
+ ...params.headers
1269
+ } },
1270
+ auditContext: "msteams.graph.absolute"
1271
+ });
1272
+ try {
1273
+ if (!response.ok) {
1274
+ const text = await response.text().catch(() => "");
1275
+ throw new Error(`Graph ${params.url} failed (${response.status}): ${text || "unknown error"}`);
1276
+ }
1277
+ return await readProviderJsonResponse(response, `Graph ${params.url} failed`);
1278
+ } finally {
1279
+ await release();
1280
+ }
1281
+ }
1282
+ /**
1283
+ * Fetch all pages of a Graph API collection, following @odata.nextLink.
1284
+ * Optionally stop early when `findOne` matches an item.
1285
+ */
1286
+ async function fetchAllGraphPages(params) {
1287
+ const maxPages = params.maxPages ?? 50;
1288
+ const items = [];
1289
+ let nextPath = params.path;
1290
+ for (let page = 0; page < maxPages && nextPath; page++) {
1291
+ const res = await fetchGraphJson({
1292
+ token: params.token,
1293
+ path: nextPath,
1294
+ headers: params.headers
1295
+ });
1296
+ const pageItems = res.value ?? [];
1297
+ if (params.findOne) {
1298
+ const match = pageItems.find(params.findOne);
1299
+ if (match) {
1300
+ items.push(...pageItems);
1301
+ return {
1302
+ items,
1303
+ truncated: false,
1304
+ found: match
1305
+ };
1306
+ }
1307
+ }
1308
+ items.push(...pageItems);
1309
+ const rawNext = res["@odata.nextLink"];
1310
+ if (rawNext) nextPath = rawNext.replace("https://graph.microsoft.com/v1.0", "").replace("https://graph.microsoft.com/beta", "");
1311
+ else nextPath = void 0;
1312
+ }
1313
+ return {
1314
+ items,
1315
+ truncated: Boolean(nextPath)
1316
+ };
1317
+ }
1318
+ async function resolveGraphToken(cfg, options) {
1319
+ const msteamsCfg = cfg?.channels?.msteams;
1320
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
1321
+ if (!creds) throw new Error("MS Teams credentials missing");
1322
+ if (options?.preferDelegated && msteamsCfg?.delegatedAuth?.enabled && creds.type === "secret") {
1323
+ const delegated = await resolveDelegatedAccessToken({
1324
+ tenantId: creds.tenantId,
1325
+ clientId: creds.appId,
1326
+ clientSecret: creds.appPassword
1327
+ });
1328
+ if (delegated) return delegated;
1329
+ }
1330
+ const { app } = await loadMSTeamsSdkWithAuth(creds);
1331
+ const accessToken = readAccessToken(await createMSTeamsTokenProvider(app).getAccessToken("https://graph.microsoft.com"));
1332
+ if (!accessToken) throw new Error("MS Teams graph token unavailable");
1333
+ return accessToken;
1334
+ }
1335
+ async function listTeamsByName(token, query) {
1336
+ const filter = `resourceProvisioningOptions/Any(x:x eq 'Team') and startsWith(displayName,'${escapeOData(query)}')`;
1337
+ const { items } = await fetchAllGraphPages({
1338
+ token,
1339
+ path: `/groups?$filter=${encodeURIComponent(filter)}&$select=id,displayName`,
1340
+ maxPages: 5
1341
+ });
1342
+ return items;
1343
+ }
1344
+ async function postGraphJson(params) {
1345
+ return readOptionalGraphJson(await requestGraph({
1346
+ token: params.token,
1347
+ path: params.path,
1348
+ method: "POST",
1349
+ body: params.body,
1350
+ errorPrefix: "Graph POST"
1351
+ }), `Graph POST ${params.path} failed`);
1352
+ }
1353
+ async function postGraphBetaJson(params) {
1354
+ return readOptionalGraphJson(await requestGraph({
1355
+ token: params.token,
1356
+ path: params.path,
1357
+ method: "POST",
1358
+ root: GRAPH_BETA,
1359
+ body: params.body,
1360
+ errorPrefix: "Graph beta POST"
1361
+ }), `Graph beta POST ${params.path} failed`);
1362
+ }
1363
+ async function deleteGraphRequest(params) {
1364
+ await requestGraph({
1365
+ token: params.token,
1366
+ path: params.path,
1367
+ method: "DELETE",
1368
+ errorPrefix: "Graph DELETE"
1369
+ });
1370
+ }
1371
+ async function patchGraphJson(params) {
1372
+ return readOptionalGraphJson(await requestGraph({
1373
+ token: params.token,
1374
+ path: params.path,
1375
+ method: "PATCH",
1376
+ body: params.body,
1377
+ errorPrefix: "Graph PATCH"
1378
+ }), `Graph PATCH ${params.path} failed`);
1379
+ }
1380
+ async function listChannelsForTeam(token, teamId) {
1381
+ const { items } = await fetchAllGraphPages({
1382
+ token,
1383
+ path: `/teams/${encodeURIComponent(teamId)}/channels?$select=id,displayName`,
1384
+ maxPages: 10
1385
+ });
1386
+ return items;
1387
+ }
1388
+ //#endregion
1389
+ //#region extensions/msteams/src/graph-users.ts
1390
+ async function searchGraphUsers(params) {
1391
+ const query = params.query.trim();
1392
+ if (!query) return [];
1393
+ if (query.includes("@")) {
1394
+ const escaped = escapeOData(query);
1395
+ const filter = `(mail eq '${escaped}' or userPrincipalName eq '${escaped}')`;
1396
+ const path = `/users?$filter=${encodeURIComponent(filter)}&$select=id,displayName,mail,userPrincipalName`;
1397
+ return (await fetchGraphJson({
1398
+ token: params.token,
1399
+ path
1400
+ })).value ?? [];
1401
+ }
1402
+ const top = typeof params.top === "number" && params.top > 0 ? params.top : 10;
1403
+ const path = `/users?$search=${encodeURIComponent(`"displayName:${query}"`)}&$select=id,displayName,mail,userPrincipalName&$top=${top}`;
1404
+ return (await fetchGraphJson({
1405
+ token: params.token,
1406
+ path,
1407
+ headers: { ConsistencyLevel: "eventual" }
1408
+ })).value ?? [];
1409
+ }
1410
+ //#endregion
1411
+ export { ATTACHMENT_TAG_RE as A, isLikelyImageAttachment as B, loadMSTeamsSdkWithAuth as C, formatMSTeamsSendErrorHint as D, classifyMSTeamsSendError as E, estimateBase64DecodedBytes as F, resolveAttachmentFetchPolicy as G, isUrlAllowed as H, extractHtmlFromAttachment as I, safeFetchWithPolicy as J, resolveMediaSsrfPolicy as K, extractInlineImageCandidates as L, IMG_SRC_RE as M, applyAuthorizationHeaderForUrl as N, formatUnknownError as O, encodeGraphShareId as P, inferPlaceholder as R, createMSTeamsTokenProvider as S, ensureUserAgentHeader as T, normalizeContentType as U, isRecord$2 as V, readNestedString as W, tryBuildGraphSharesUrlForSharedLink as X, safeHostForUrl as Y, resolveMSTeamsStorePath as _, fetchGraphJson as a, createBotFrameworkJwtValidator as b, normalizeQuery as c, postGraphJson as d, resolveGraphToken as f, saveDelegatedTokens as g, resolveMSTeamsCredentials as h, fetchGraphAbsoluteUrl as i, GRAPH_ROOT as j, isRevokedProxyError as k, patchGraphJson as l, loadDelegatedTokens as m, deleteGraphRequest as n, listChannelsForTeam as o, hasConfiguredMSTeamsCredentials as p, resolveRequestUrl as q, escapeOData as r, listTeamsByName as s, searchGraphUsers as t, postGraphBetaJson as u, normalizeSecretInputString as v, buildUserAgent as w, createMSTeamsAdapter as x, readAccessToken as y, isDownloadableAttachment as z };