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