@kodelyth/msteams 2026.5.42 → 2026.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +18 -6
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
package/src/sdk.test.ts DELETED
@@ -1,727 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
- import {
4
- createBotFrameworkJwtValidator,
5
- createMSTeamsAdapter,
6
- createMSTeamsApp,
7
- type MSTeamsTeamsSdk,
8
- } from "./sdk.js";
9
- import type {
10
- MSTeamsCredentials,
11
- MSTeamsSecretCredentials,
12
- MSTeamsFederatedCredentials,
13
- } from "./token.js";
14
-
15
- vi.mock("klaw/plugin-sdk/ssrf-runtime", async () => {
16
- const actual = await vi.importActual<typeof import("klaw/plugin-sdk/ssrf-runtime")>(
17
- "klaw/plugin-sdk/ssrf-runtime",
18
- );
19
- return {
20
- ...actual,
21
- fetchWithSsrFGuard: async (params: {
22
- url: string;
23
- init?: RequestInit;
24
- fetchImpl?: typeof fetch;
25
- }) => ({
26
- response: await (params.fetchImpl ?? fetch)(params.url, params.init),
27
- finalUrl: params.url,
28
- release: async () => {},
29
- }),
30
- };
31
- });
32
-
33
- const clientConstructorState = vi.hoisted(() => ({
34
- calls: [] as Array<{ serviceUrl: string; options: unknown }>,
35
- }));
36
-
37
- // Track jwt.verify calls to assert audience/issuer/algorithm config.
38
- const jwtState = vi.hoisted(() => ({
39
- verifyBehavior: "success" as "success" | "throw",
40
- decodedHeader: { kid: "key-1" } as { kid?: string } | null,
41
- decodedPayload: { iss: "https://api.botframework.com" } as { iss?: string } | string | null,
42
- verifyResult: { sub: "ok" } as unknown,
43
- verifyCalls: [] as Array<{ token: string; options: unknown }>,
44
- }));
45
-
46
- const jwtMockImpl = {
47
- decode: (token: string, opts?: { complete?: boolean }) => {
48
- if (opts?.complete) {
49
- return jwtState.decodedHeader ? { header: jwtState.decodedHeader } : null;
50
- }
51
- return jwtState.decodedPayload;
52
- },
53
- verify: (token: string, _key: string, options: unknown) => {
54
- jwtState.verifyCalls.push({ token, options });
55
- if (jwtState.verifyBehavior === "throw") {
56
- throw new Error("invalid signature");
57
- }
58
- return jwtState.verifyResult;
59
- },
60
- };
61
-
62
- vi.mock("jsonwebtoken", () => ({
63
- // Match jsonwebtoken@9 under dynamic ESM import from plugin package deps:
64
- // Node exposes decode as a named export, while verify is only on default.
65
- decode: jwtMockImpl.decode,
66
- default: jwtMockImpl,
67
- }));
68
-
69
- vi.mock("jwks-rsa", () => ({
70
- JwksClient: class JwksClient {
71
- async getSigningKey(_kid: string) {
72
- return { getPublicKey: () => "mock-public-key" };
73
- }
74
- },
75
- }));
76
-
77
- vi.mock("node:fs", async (importOriginal) => {
78
- const actual = await importOriginal<typeof import("node:fs")>();
79
- return {
80
- ...actual,
81
- readFileSync: vi.fn(
82
- () => "-----BEGIN RSA PRIVATE KEY-----\nfake-key\n-----END RSA PRIVATE KEY-----",
83
- ),
84
- };
85
- });
86
-
87
- const { mockGetToken } = vi.hoisted(() => {
88
- const mockGetToken = vi.fn().mockResolvedValue({ token: "mock-managed-token" });
89
- return { mockGetToken };
90
- });
91
- vi.mock("@azure/identity", () => {
92
- // Use classes so `new ...Credential()` works after vitest hoisting
93
- // (function declarations inside vi.mock factories can be transformed
94
- // into arrow functions during hoisting, which breaks `new`).
95
- class ManagedIdentityCredential {
96
- getToken = mockGetToken;
97
- }
98
- class DefaultAzureCredential {
99
- getToken = mockGetToken;
100
- }
101
- class ClientCertificateCredential {
102
- getToken = mockGetToken;
103
- }
104
- return { ManagedIdentityCredential, DefaultAzureCredential, ClientCertificateCredential };
105
- });
106
-
107
- const originalFetch = globalThis.fetch;
108
-
109
- afterEach(() => {
110
- globalThis.fetch = originalFetch;
111
- clientConstructorState.calls.length = 0;
112
- jwtState.verifyCalls.length = 0;
113
- jwtState.verifyBehavior = "success";
114
- jwtState.decodedHeader = { kid: "key-1" };
115
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
116
- jwtState.verifyResult = { sub: "ok" };
117
- vi.restoreAllMocks();
118
- });
119
-
120
- function createSdkStub(): MSTeamsTeamsSdk {
121
- class AppStub {
122
- async getBotToken() {
123
- return {
124
- toString() {
125
- return "bot-token";
126
- },
127
- };
128
- }
129
- }
130
-
131
- class ClientStub {
132
- constructor(serviceUrl: string, options: unknown) {
133
- clientConstructorState.calls.push({ serviceUrl, options });
134
- }
135
-
136
- conversations = {
137
- activities: (_conversationId: string) => ({
138
- create: async (_activity: unknown) => ({ id: "created" }),
139
- }),
140
- };
141
- }
142
-
143
- return {
144
- App: AppStub as unknown as MSTeamsTeamsSdk["App"],
145
- Client: ClientStub as unknown as MSTeamsTeamsSdk["Client"],
146
- };
147
- }
148
-
149
- function requireFirstAppInstance(appInstances: Record<string, unknown>[]) {
150
- const appInstance = appInstances[0];
151
- if (!appInstance) {
152
- throw new Error("expected sdk.App constructor call");
153
- }
154
- return appInstance;
155
- }
156
-
157
- function readFirstFetchCall(
158
- fetchMock: ReturnType<typeof vi.fn>,
159
- ): [string, { method?: string; headers: { Authorization?: string } }] {
160
- const [call] = fetchMock.mock.calls;
161
- if (!call) {
162
- throw new Error("expected fetch call");
163
- }
164
- const [url, options] = call;
165
- if (typeof url !== "string" || !options || typeof options !== "object") {
166
- throw new Error("expected fetch URL and options");
167
- }
168
- if (!("headers" in options) || !options.headers || typeof options.headers !== "object") {
169
- throw new Error("expected fetch options headers");
170
- }
171
- return [url, options as { method?: string; headers: { Authorization?: string } }];
172
- }
173
-
174
- function readFirstCreatedActivity(createFn: ReturnType<typeof vi.fn>): {
175
- type?: string;
176
- text?: string;
177
- } {
178
- const [call] = createFn.mock.calls;
179
- if (!call) {
180
- throw new Error("expected activity create call");
181
- }
182
- const [activity] = call;
183
- if (!activity || typeof activity !== "object") {
184
- throw new Error("expected created activity payload");
185
- }
186
- return activity as { type?: string; text?: string };
187
- }
188
-
189
- describe("createMSTeamsApp", () => {
190
- it("creates app without the Express 5 wildcard route regression (#55161)", async () => {
191
- // Regression test for: https://github.com/klaw/klaw/issues/55161
192
- // createMSTeamsApp passes a no-op httpServerAdapter to prevent the SDK from
193
- // creating its default HttpPlugin (which registers `/api*` — invalid in Express 5).
194
- const { App } = await import("@microsoft/teams.apps");
195
- const { Client } = await import("@microsoft/teams.api");
196
- const sdk: MSTeamsTeamsSdk = { App, Client };
197
- const creds: MSTeamsCredentials = {
198
- type: "secret",
199
- appId: "test-app-id",
200
- appPassword: "test-secret",
201
- tenantId: "test-tenant",
202
- };
203
-
204
- // This would throw "Missing parameter name at index 5: /api*" without the fix
205
- const app = await createMSTeamsApp(creds, sdk);
206
- // Verify token methods are available (the reason we use the App class)
207
- expect(typeof (app as unknown as Record<string, unknown>).getBotToken).toBe("function");
208
- });
209
- });
210
-
211
- describe("createMSTeamsAdapter", () => {
212
- it("provides deleteActivity in proactive continueConversation contexts", async () => {
213
- const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));
214
- globalThis.fetch = fetchMock as unknown as typeof fetch;
215
-
216
- const creds = {
217
- appId: "app-id",
218
- type: "secret",
219
- appPassword: "secret",
220
- tenantId: "tenant-id",
221
- } satisfies MSTeamsCredentials;
222
- const sdk = createSdkStub();
223
- const app = new sdk.App({
224
- clientId: creds.appId,
225
- clientSecret: creds.appPassword,
226
- tenantId: creds.tenantId,
227
- });
228
- const adapter = createMSTeamsAdapter(app, sdk);
229
-
230
- await adapter.continueConversation(
231
- creds.appId,
232
- {
233
- serviceUrl: "https://example.com/",
234
- conversation: { id: "19:conversation@thread.tacv2" },
235
- channelId: "msteams",
236
- },
237
- async (ctx) => {
238
- await ctx.deleteActivity("activity-123");
239
- },
240
- );
241
-
242
- expect(fetchMock).toHaveBeenCalledTimes(1);
243
- const [url, options] = readFirstFetchCall(fetchMock);
244
- expect(url).toBe(
245
- "https://example.com/v3/conversations/19%3Aconversation%40thread.tacv2/activities/activity-123",
246
- );
247
- expect(options.method).toBe("DELETE");
248
- expect(options.headers?.Authorization).toBe("Bearer bot-token");
249
- });
250
-
251
- it("passes the Klaw User-Agent to the Bot Framework connector client", async () => {
252
- const creds = {
253
- type: "secret",
254
- appId: "app-id",
255
- appPassword: "secret",
256
- tenantId: "tenant-id",
257
- } satisfies MSTeamsCredentials;
258
- const sdk = createSdkStub();
259
- const app = new sdk.App({
260
- clientId: creds.appId,
261
- clientSecret: creds.appPassword,
262
- tenantId: creds.tenantId,
263
- });
264
- const adapter = createMSTeamsAdapter(app, sdk);
265
-
266
- await adapter.continueConversation(
267
- creds.appId,
268
- {
269
- serviceUrl: "https://service.example.com/",
270
- conversation: { id: "19:conversation@thread.tacv2" },
271
- channelId: "msteams",
272
- },
273
- async (ctx) => {
274
- await ctx.sendActivity("hello");
275
- },
276
- );
277
-
278
- expect(clientConstructorState.calls).toHaveLength(1);
279
- const clientCall = clientConstructorState.calls[0];
280
- expect(clientCall?.serviceUrl).toBe("https://service.example.com/");
281
- const options = clientCall?.options as { headers?: { "User-Agent"?: string } } | undefined;
282
- expect(options?.headers?.["User-Agent"]).toMatch(/^teams\.ts\[apps\]\/.+ Klaw\/.+$/);
283
- });
284
- });
285
-
286
- describe("createBotFrameworkJwtValidator", () => {
287
- const creds = {
288
- appId: "app-id",
289
- type: "secret",
290
- appPassword: "secret",
291
- tenantId: "tenant-id",
292
- } satisfies MSTeamsCredentials;
293
-
294
- it("validates a token with Bot Framework issuer and correct audience list", async () => {
295
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
296
-
297
- const validator = await createBotFrameworkJwtValidator(creds);
298
- await expect(validator.validate("Bearer token-bf")).resolves.toBe(true);
299
-
300
- expect(jwtState.verifyCalls).toHaveLength(1);
301
- const opts = jwtState.verifyCalls[0]?.options as Record<string, unknown>;
302
- expect(opts.audience).toEqual(["app-id", "api://app-id", "https://api.botframework.com"]);
303
- expect(opts.algorithms).toEqual(["RS256"]);
304
- expect(opts.clockTolerance).toBe(300);
305
- });
306
-
307
- it("accepts tokens with aud: https://api.botframework.com (#58249)", async () => {
308
- // This is the critical fix: the old JwtValidator rejected this audience.
309
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
310
- jwtState.verifyResult = {
311
- aud: ["https://api.botframework.com"],
312
- appid: creds.appId,
313
- };
314
-
315
- const validator = await createBotFrameworkJwtValidator(creds);
316
- await expect(validator.validate("Bearer botfw-token")).resolves.toBe(true);
317
-
318
- const opts = jwtState.verifyCalls[0]?.options as Record<string, unknown>;
319
- expect(opts.audience).toContain("https://api.botframework.com");
320
- });
321
-
322
- it("accepts global audience tokens when azp matches the configured app id", async () => {
323
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
324
- jwtState.verifyResult = {
325
- aud: ["https://api.botframework.com"],
326
- azp: "APP-ID",
327
- };
328
-
329
- const validator = await createBotFrameworkJwtValidator(creds);
330
- await expect(validator.validate("Bearer botfw-token-azp")).resolves.toBe(true);
331
- });
332
-
333
- it("rejects global audience tokens when app binding does not match the configured app id", async () => {
334
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
335
- jwtState.verifyResult = {
336
- aud: ["https://api.botframework.com"],
337
- azp: "other-app-id",
338
- };
339
-
340
- const validator = await createBotFrameworkJwtValidator(creds);
341
- await expect(validator.validate("Bearer botfw-token-wrong-app")).resolves.toBe(false);
342
- });
343
-
344
- it("rejects non-object verified payloads", async () => {
345
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
346
- jwtState.verifyResult = "verified-string-payload";
347
-
348
- const validator = await createBotFrameworkJwtValidator(creds);
349
- await expect(validator.validate("Bearer botfw-token-string")).resolves.toBe(false);
350
- });
351
-
352
- it("validates a token with Entra issuer", async () => {
353
- jwtState.decodedPayload = { iss: `https://login.microsoftonline.com/tenant-id/v2.0` };
354
-
355
- const validator = await createBotFrameworkJwtValidator(creds);
356
- await expect(validator.validate("Bearer token-entra")).resolves.toBe(true);
357
-
358
- expect(jwtState.verifyCalls).toHaveLength(1);
359
- const opts = jwtState.verifyCalls[0]?.options as Record<string, unknown>;
360
- expect(opts.issuer as string[]).toContain("https://login.microsoftonline.com/tenant-id/v2.0");
361
- });
362
-
363
- it("validates a SingleTenant token with tenant-scoped STS Windows issuer (#64270)", async () => {
364
- // Regression for #64270: the sts.windows.net issuer was hardcoded to a
365
- // single tenant UUID, so every other SingleTenant bot deployment hit 401.
366
- // The tenant-aware form must accept the deployment's own tenant.
367
- jwtState.decodedPayload = {
368
- iss: `https://sts.windows.net/${creds.tenantId}/`,
369
- };
370
-
371
- const validator = await createBotFrameworkJwtValidator(creds);
372
- await expect(validator.validate("Bearer token-sts")).resolves.toBe(true);
373
-
374
- expect(jwtState.verifyCalls).toHaveLength(1);
375
- const opts = jwtState.verifyCalls[0]?.options as Record<string, unknown>;
376
- expect(opts.issuer as string[]).toContain(`https://sts.windows.net/${creds.tenantId}/`);
377
- });
378
-
379
- it("rejects STS Windows tokens issued by a different tenant (#64270)", async () => {
380
- // Guardrail against regressing back to a hardcoded tenant: the previously
381
- // hardcoded UUID must NOT be accepted when the bot is configured for a
382
- // different tenant. This also prevents cross-tenant token reuse.
383
- jwtState.decodedPayload = {
384
- iss: "https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/",
385
- };
386
-
387
- const validator = await createBotFrameworkJwtValidator(creds);
388
- await expect(validator.validate("Bearer token-sts-other-tenant")).resolves.toBe(false);
389
- expect(jwtState.verifyCalls).toHaveLength(0);
390
- });
391
-
392
- it("rejects tokens with unknown issuer", async () => {
393
- jwtState.decodedPayload = { iss: "https://evil.example.com" };
394
-
395
- const validator = await createBotFrameworkJwtValidator(creds);
396
- await expect(validator.validate("Bearer token-evil")).resolves.toBe(false);
397
- expect(jwtState.verifyCalls).toHaveLength(0);
398
- });
399
-
400
- it("returns false when signature verification fails", async () => {
401
- jwtState.verifyBehavior = "throw";
402
-
403
- const validator = await createBotFrameworkJwtValidator(creds);
404
- await expect(validator.validate("Bearer token-bad")).resolves.toBe(false);
405
- });
406
-
407
- it("returns false for empty bearer token", async () => {
408
- const validator = await createBotFrameworkJwtValidator(creds);
409
- await expect(validator.validate("Bearer ")).resolves.toBe(false);
410
- expect(jwtState.verifyCalls).toHaveLength(0);
411
- });
412
-
413
- it("returns false when token has no kid header", async () => {
414
- jwtState.decodedHeader = { kid: undefined };
415
-
416
- const validator = await createBotFrameworkJwtValidator(creds);
417
- await expect(validator.validate("Bearer no-kid")).resolves.toBe(false);
418
- expect(jwtState.verifyCalls).toHaveLength(0);
419
- });
420
-
421
- it("returns false when token has no issuer claim", async () => {
422
- jwtState.decodedPayload = { iss: undefined };
423
-
424
- const validator = await createBotFrameworkJwtValidator(creds);
425
- await expect(validator.validate("Bearer no-iss")).resolves.toBe(false);
426
- expect(jwtState.verifyCalls).toHaveLength(0);
427
- });
428
-
429
- it("rethrows JWKS network errors (ECONNREFUSED) instead of silently returning false (#77674)", async () => {
430
- // Simulate a firewall blocking egress to login.botframework.com.
431
- // The top-level vi.mock("jwks-rsa") sets up a class-level mock, so we spy
432
- // on the prototype to override getSigningKey for this test only.
433
- const networkErr = Object.assign(new Error("connect ECONNREFUSED 40.126.25.32:443"), {
434
- code: "ECONNREFUSED",
435
- });
436
- const { JwksClient } = await import("jwks-rsa");
437
- vi.spyOn(JwksClient.prototype, "getSigningKey").mockRejectedValueOnce(networkErr);
438
-
439
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
440
- const validator = await createBotFrameworkJwtValidator(creds);
441
- // Network errors must bubble out — callers can then log them at warn/error
442
- // level rather than silently returning 401 that looks like a bad credential.
443
- await expect(validator.validate("Bearer token-firewall")).rejects.toThrow("ECONNREFUSED");
444
- });
445
-
446
- it("returns false (not throws) for non-network JWKS errors like bad signature (#77674)", async () => {
447
- // Auth errors (bad signature, expired token) should still return false.
448
- jwtState.decodedPayload = { iss: "https://api.botframework.com" };
449
- jwtState.verifyBehavior = "throw";
450
- const validator = await createBotFrameworkJwtValidator(creds);
451
- await expect(validator.validate("Bearer token-bad-sig")).resolves.toBe(false);
452
- });
453
- });
454
-
455
- function makeFakeSdk() {
456
- const appInstances: Record<string, unknown>[] = [];
457
- const FakeClient = function FakeClient() {};
458
- const FakeApp = class {
459
- opts: Record<string, unknown>;
460
- constructor(opts: Record<string, unknown>) {
461
- this.opts = opts;
462
- appInstances.push(opts);
463
- }
464
- };
465
- return { sdk: { App: FakeApp as any, Client: FakeClient as any }, appInstances, FakeApp };
466
- }
467
-
468
- describe("createMSTeamsApp – secret credentials", () => {
469
- it("passes clientId, clientSecret, tenantId to sdk.App", async () => {
470
- const { sdk, appInstances, FakeApp } = makeFakeSdk();
471
- const creds: MSTeamsSecretCredentials = {
472
- type: "secret",
473
- appId: "my-app-id",
474
- appPassword: "my-secret",
475
- tenantId: "my-tenant",
476
- };
477
- const app = await createMSTeamsApp(creds, sdk);
478
- expect(app).toBeInstanceOf(FakeApp);
479
- const appInstance = requireFirstAppInstance(appInstances);
480
- expect(appInstance.clientId).toBe("my-app-id");
481
- expect(appInstance.clientSecret).toBe("my-secret");
482
- expect(appInstance.tenantId).toBe("my-tenant");
483
- });
484
- });
485
-
486
- describe("createMSTeamsApp – federated certificate credentials", () => {
487
- beforeEach(() => {
488
- vi.mocked(fs.readFileSync).mockReturnValue(
489
- "-----BEGIN RSA PRIVATE KEY-----\nfake-key\n-----END RSA PRIVATE KEY-----",
490
- );
491
- });
492
-
493
- it("reads the certificate and creates app with token function", async () => {
494
- const { sdk, appInstances } = makeFakeSdk();
495
- const creds: MSTeamsFederatedCredentials = {
496
- type: "federated",
497
- appId: "fed-app-id",
498
- tenantId: "fed-tenant",
499
- certificatePath: "/certs/bot.pem",
500
- certificateThumbprint: "AABB1122",
501
- };
502
- await createMSTeamsApp(creds, sdk);
503
- expect(fs.readFileSync).toHaveBeenCalledWith("/certs/bot.pem", "utf-8");
504
- const appInstance = requireFirstAppInstance(appInstances);
505
- expect(appInstance.clientId).toBe("fed-app-id");
506
- expect(appInstance.tenantId).toBe("fed-tenant");
507
- const tokenProvider = appInstance.token as ((scope: string) => Promise<string>) | undefined;
508
- if (!tokenProvider) {
509
- throw new Error("expected federated app to expose token provider");
510
- }
511
- const token = await tokenProvider("https://api.botframework.com/.default");
512
- expect(token).toBe("mock-managed-token");
513
- });
514
-
515
- it("wraps readFileSync errors with descriptive message", async () => {
516
- vi.mocked(fs.readFileSync).mockImplementation(() => {
517
- throw new Error("ENOENT: no such file or directory");
518
- });
519
- const { sdk } = makeFakeSdk();
520
- const creds: MSTeamsFederatedCredentials = {
521
- type: "federated",
522
- appId: "fed-app-id",
523
- tenantId: "fed-tenant",
524
- certificatePath: "/missing/cert.pem",
525
- };
526
- await expect(async () => await createMSTeamsApp(creds, sdk)).rejects.toThrow(
527
- /Failed to read certificate file at '\/missing\/cert\.pem'/,
528
- );
529
- });
530
-
531
- it("throws when federated but no certificatePath and no managedIdentity", async () => {
532
- const { sdk } = makeFakeSdk();
533
- const creds: MSTeamsFederatedCredentials = {
534
- type: "federated",
535
- appId: "fed-app-id",
536
- tenantId: "fed-tenant",
537
- };
538
- await expect(async () => await createMSTeamsApp(creds, sdk)).rejects.toThrow(
539
- /certificate path or managed identity/i,
540
- );
541
- });
542
- });
543
-
544
- describe("createMSTeamsApp – federated managed identity", () => {
545
- it("creates app with token function for user-assigned MI", async () => {
546
- const { sdk, appInstances } = makeFakeSdk();
547
- const creds: MSTeamsFederatedCredentials = {
548
- type: "federated",
549
- appId: "mi-app-id",
550
- tenantId: "mi-tenant",
551
- useManagedIdentity: true,
552
- managedIdentityClientId: "mi-client-id",
553
- };
554
- await createMSTeamsApp(creds, sdk);
555
- const appInstance = requireFirstAppInstance(appInstances);
556
- expect(appInstance.clientId).toBe("mi-app-id");
557
- expect(appInstance.tenantId).toBe("mi-tenant");
558
- const tokenProvider = appInstance.token as ((scope: string) => Promise<string>) | undefined;
559
- if (!tokenProvider) {
560
- throw new Error("expected managed-identity app to expose token provider");
561
- }
562
- const token = await tokenProvider("https://api.botframework.com/.default");
563
- expect(token).toBe("mock-managed-token");
564
- });
565
-
566
- it("creates app with token function for system-assigned MI", async () => {
567
- const { sdk, appInstances } = makeFakeSdk();
568
- const creds: MSTeamsFederatedCredentials = {
569
- type: "federated",
570
- appId: "mi-app-id",
571
- tenantId: "mi-tenant",
572
- useManagedIdentity: true,
573
- };
574
- await createMSTeamsApp(creds, sdk);
575
- const tokenProvider = appInstances[0].token as ((scope: string) => Promise<string>) | undefined;
576
- if (!tokenProvider) {
577
- throw new Error("expected managed-identity app to expose token provider");
578
- }
579
- const token = await tokenProvider("https://api.botframework.com/.default");
580
- expect(token).toBe("mock-managed-token");
581
- });
582
-
583
- it("throws from token function when token acquisition fails", async () => {
584
- mockGetToken.mockResolvedValueOnce(null);
585
- const { sdk, appInstances } = makeFakeSdk();
586
- const creds: MSTeamsFederatedCredentials = {
587
- type: "federated",
588
- appId: "mi-app-id",
589
- tenantId: "mi-tenant",
590
- useManagedIdentity: true,
591
- };
592
- await createMSTeamsApp(creds, sdk);
593
- const tokenFn = appInstances[0].token as (scope: string) => Promise<string>;
594
- await expect(tokenFn("https://api.botframework.com/.default")).rejects.toThrow(
595
- /failed to acquire token/i,
596
- );
597
- });
598
- });
599
-
600
- // ── createMSTeamsAdapter tests ─────────────────────────────────────────────
601
-
602
- function makeFakeApp() {
603
- return {
604
- getBotToken: vi.fn().mockResolvedValue({ toString: () => "fake-bot-token" }),
605
- } as any;
606
- }
607
-
608
- function makeFakeApiSdk() {
609
- const createFn = vi.fn().mockResolvedValue({ id: "new-activity-id" });
610
- const FakeApp = function FakeApp() {};
611
- const FakeClient = class {
612
- conversations = {
613
- activities: (_convId: string) => ({ create: createFn }),
614
- };
615
- };
616
- return {
617
- sdk: { App: FakeApp as any, Client: FakeClient as any },
618
- createFn,
619
- };
620
- }
621
-
622
- describe("createMSTeamsAdapter – continueConversation", () => {
623
- const originalFetch = globalThis.fetch;
624
-
625
- afterEach(() => {
626
- globalThis.fetch = originalFetch;
627
- vi.restoreAllMocks();
628
- });
629
-
630
- it("provides sendActivity via REST API client in logic callback", async () => {
631
- const { sdk, createFn } = makeFakeApiSdk();
632
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
633
-
634
- const reference = {
635
- serviceUrl: "https://smba.trafficmanager.net/teams/",
636
- conversation: { id: "conv-123", conversationType: "personal" },
637
- channelId: "msteams",
638
- };
639
-
640
- await adapter.continueConversation("app-id", reference, async (ctx) => {
641
- await ctx.sendActivity("hello from proactive send");
642
- });
643
-
644
- expect(createFn).toHaveBeenCalledTimes(1);
645
- const activity = readFirstCreatedActivity(createFn);
646
- expect(activity.type).toBe("message");
647
- expect(activity.text).toBe("hello from proactive send");
648
- });
649
-
650
- it("provides deleteActivity via REST DELETE in logic callback", async () => {
651
- const mockFetch = vi.fn().mockResolvedValue({ ok: true });
652
- globalThis.fetch = mockFetch;
653
- const { sdk } = makeFakeApiSdk();
654
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
655
-
656
- const reference = {
657
- serviceUrl: "https://smba.trafficmanager.net/teams/",
658
- conversation: { id: "conv-456", conversationType: "personal" },
659
- channelId: "msteams",
660
- };
661
-
662
- await adapter.continueConversation("app-id", reference, async (ctx) => {
663
- await ctx.deleteActivity("activity-789");
664
- });
665
-
666
- expect(mockFetch).toHaveBeenCalledTimes(1);
667
- const [url, opts] = readFirstFetchCall(mockFetch);
668
- expect(url).toContain("/v3/conversations/conv-456/activities/activity-789");
669
- expect(opts.method).toBe("DELETE");
670
- expect(opts.headers.Authorization).toBe("Bearer fake-bot-token");
671
- });
672
-
673
- it("throws when serviceUrl is missing", async () => {
674
- const { sdk } = makeFakeApiSdk();
675
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
676
-
677
- await expect(
678
- adapter.continueConversation("app-id", { conversation: { id: "c" } } as any, async () => {}),
679
- ).rejects.toThrow(/Missing serviceUrl/);
680
- });
681
-
682
- it("throws when conversation.id is missing", async () => {
683
- const { sdk } = makeFakeApiSdk();
684
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
685
-
686
- await expect(
687
- adapter.continueConversation(
688
- "app-id",
689
- { serviceUrl: "https://example.com" } as any,
690
- async () => {},
691
- ),
692
- ).rejects.toThrow(/Missing conversation\.id/);
693
- });
694
- });
695
-
696
- describe("createMSTeamsAdapter – process", () => {
697
- it("sends 200 for normal message activities", async () => {
698
- const { sdk } = makeFakeApiSdk();
699
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
700
-
701
- const req = { body: { type: "message", text: "hi" } };
702
- const sendFn = vi.fn();
703
- const res = { status: vi.fn(() => ({ send: sendFn })) };
704
-
705
- await adapter.process(req, res, async () => {});
706
-
707
- expect(res.status).toHaveBeenCalledWith(200);
708
- expect(sendFn).toHaveBeenCalled();
709
- });
710
-
711
- it("sends 200 immediately for invoke activities", async () => {
712
- const { sdk } = makeFakeApiSdk();
713
- const adapter = createMSTeamsAdapter(makeFakeApp(), sdk);
714
-
715
- const req = { body: { type: "invoke", name: "adaptiveCard/action" } };
716
- const sendFn = vi.fn();
717
- const res = { status: vi.fn(() => ({ send: sendFn })) };
718
-
719
- let statusCalledBeforeLogic = false;
720
- await adapter.process(req, res, async () => {
721
- statusCalledBeforeLogic = res.status.mock.calls.length > 0;
722
- });
723
-
724
- expect(statusCalledBeforeLogic).toBe(true);
725
- expect(res.status).toHaveBeenCalledWith(200);
726
- });
727
- });