@gakr-gakr/msteams 0.1.0

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 (107) hide show
  1. package/api.ts +3 -0
  2. package/autobot.plugin.json +15 -0
  3. package/channel-config-api.ts +1 -0
  4. package/channel-plugin-api.ts +2 -0
  5. package/config-api.ts +4 -0
  6. package/contract-api.ts +4 -0
  7. package/index.ts +20 -0
  8. package/package.json +72 -0
  9. package/runtime-api.ts +66 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.ts +348 -0
  16. package/src/attachments/download.ts +328 -0
  17. package/src/attachments/graph.ts +489 -0
  18. package/src/attachments/html.ts +122 -0
  19. package/src/attachments/payload.ts +14 -0
  20. package/src/attachments/remote-media.ts +86 -0
  21. package/src/attachments/shared.ts +655 -0
  22. package/src/attachments/types.ts +47 -0
  23. package/src/attachments.ts +18 -0
  24. package/src/channel-api.ts +1 -0
  25. package/src/channel.runtime.ts +56 -0
  26. package/src/channel.setup.ts +77 -0
  27. package/src/channel.ts +1176 -0
  28. package/src/config-schema.ts +6 -0
  29. package/src/config-ui-hints.ts +40 -0
  30. package/src/conversation-store-fs.ts +149 -0
  31. package/src/conversation-store-helpers.ts +105 -0
  32. package/src/conversation-store-memory.ts +51 -0
  33. package/src/conversation-store.ts +71 -0
  34. package/src/directory-live.ts +111 -0
  35. package/src/doctor.ts +27 -0
  36. package/src/errors.ts +270 -0
  37. package/src/feedback-reflection-prompt.ts +117 -0
  38. package/src/feedback-reflection-store.ts +113 -0
  39. package/src/feedback-reflection.ts +271 -0
  40. package/src/file-consent-helpers.ts +115 -0
  41. package/src/file-consent-invoke.ts +150 -0
  42. package/src/file-consent.ts +223 -0
  43. package/src/graph-chat.ts +36 -0
  44. package/src/graph-group-management.ts +168 -0
  45. package/src/graph-members.ts +48 -0
  46. package/src/graph-messages.ts +534 -0
  47. package/src/graph-teams.ts +114 -0
  48. package/src/graph-thread.ts +146 -0
  49. package/src/graph-upload.ts +531 -0
  50. package/src/graph-users.ts +29 -0
  51. package/src/graph.ts +308 -0
  52. package/src/inbound.ts +148 -0
  53. package/src/index.ts +4 -0
  54. package/src/media-helpers.ts +105 -0
  55. package/src/mentions.ts +114 -0
  56. package/src/messenger.ts +608 -0
  57. package/src/monitor-handler/access.ts +136 -0
  58. package/src/monitor-handler/inbound-media.ts +180 -0
  59. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  60. package/src/monitor-handler/message-handler.test-support.ts +102 -0
  61. package/src/monitor-handler/message-handler.ts +1015 -0
  62. package/src/monitor-handler/reaction-handler.ts +124 -0
  63. package/src/monitor-handler/thread-session.ts +30 -0
  64. package/src/monitor-handler.ts +538 -0
  65. package/src/monitor-handler.types.ts +27 -0
  66. package/src/monitor-types.ts +6 -0
  67. package/src/monitor.ts +476 -0
  68. package/src/oauth.flow.ts +77 -0
  69. package/src/oauth.shared.ts +37 -0
  70. package/src/oauth.token.ts +162 -0
  71. package/src/oauth.ts +130 -0
  72. package/src/outbound.ts +198 -0
  73. package/src/pending-uploads-fs.ts +235 -0
  74. package/src/pending-uploads.ts +121 -0
  75. package/src/policy.ts +245 -0
  76. package/src/polls-store-memory.ts +32 -0
  77. package/src/polls.ts +312 -0
  78. package/src/presentation.ts +93 -0
  79. package/src/probe.ts +132 -0
  80. package/src/reply-dispatcher.ts +523 -0
  81. package/src/reply-stream-controller.ts +334 -0
  82. package/src/resolve-allowlist.ts +309 -0
  83. package/src/revoked-context.ts +17 -0
  84. package/src/runtime.ts +12 -0
  85. package/src/sdk-types.ts +59 -0
  86. package/src/sdk.ts +916 -0
  87. package/src/secret-contract.ts +49 -0
  88. package/src/secret-input.ts +7 -0
  89. package/src/send-context.ts +269 -0
  90. package/src/send.ts +697 -0
  91. package/src/sent-message-cache.ts +174 -0
  92. package/src/session-route.ts +40 -0
  93. package/src/setup-core.ts +162 -0
  94. package/src/setup-surface.ts +319 -0
  95. package/src/sso-token-store.ts +166 -0
  96. package/src/sso.ts +300 -0
  97. package/src/storage.ts +25 -0
  98. package/src/store-fs.ts +42 -0
  99. package/src/streaming-message.ts +327 -0
  100. package/src/thread-parent-context.ts +159 -0
  101. package/src/token-response.ts +11 -0
  102. package/src/token.ts +194 -0
  103. package/src/user-agent.ts +53 -0
  104. package/src/webhook-timeouts.ts +27 -0
  105. package/src/welcome-card.ts +57 -0
  106. package/test-api.ts +1 -0
  107. package/tsconfig.json +16 -0
@@ -0,0 +1,328 @@
1
+ import {
2
+ normalizeLowercaseStringOrEmpty,
3
+ normalizeOptionalLowercaseString,
4
+ normalizeOptionalString,
5
+ } from "autobot/plugin-sdk/string-coerce-runtime";
6
+ import { getMSTeamsRuntime } from "../runtime.js";
7
+ import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
8
+ import {
9
+ extractInlineImageCandidates,
10
+ inferPlaceholder,
11
+ isDownloadableAttachment,
12
+ isRecord,
13
+ isUrlAllowed,
14
+ type MSTeamsAttachmentDownloadLogger,
15
+ type MSTeamsAttachmentFetchPolicy,
16
+ type MSTeamsAttachmentResolveFn,
17
+ normalizeContentType,
18
+ resolveMediaSsrfPolicy,
19
+ resolveAttachmentFetchPolicy,
20
+ resolveRequestUrl,
21
+ safeFetchWithPolicy,
22
+ tryBuildGraphSharesUrlForSharedLink,
23
+ } from "./shared.js";
24
+ import type {
25
+ MSTeamsAccessTokenProvider,
26
+ MSTeamsAttachmentLike,
27
+ MSTeamsInboundMedia,
28
+ } from "./types.js";
29
+
30
+ type DownloadCandidate = {
31
+ url: string;
32
+ fileHint?: string;
33
+ contentTypeHint?: string;
34
+ placeholder: string;
35
+ };
36
+
37
+ function resolveDownloadCandidate(att: MSTeamsAttachmentLike): DownloadCandidate | null {
38
+ const contentType = normalizeContentType(att.contentType);
39
+ const name = normalizeOptionalString(att.name) ?? "";
40
+
41
+ if (contentType === "application/vnd.microsoft.teams.file.download.info") {
42
+ if (!isRecord(att.content)) {
43
+ return null;
44
+ }
45
+ const downloadUrl = normalizeOptionalString(att.content.downloadUrl) ?? "";
46
+ if (!downloadUrl) {
47
+ return null;
48
+ }
49
+
50
+ const fileType = normalizeOptionalString(att.content.fileType) ?? "";
51
+ const uniqueId = normalizeOptionalString(att.content.uniqueId) ?? "";
52
+ const fileName = normalizeOptionalString(att.content.fileName) ?? "";
53
+
54
+ const fileHint = name || fileName || (uniqueId && fileType ? `${uniqueId}.${fileType}` : "");
55
+ return {
56
+ url: downloadUrl,
57
+ fileHint: fileHint || undefined,
58
+ contentTypeHint: undefined,
59
+ placeholder: inferPlaceholder({
60
+ contentType,
61
+ fileName: fileHint,
62
+ fileType,
63
+ }),
64
+ };
65
+ }
66
+
67
+ const contentUrl = normalizeOptionalString(att.contentUrl) ?? "";
68
+ if (!contentUrl) {
69
+ return null;
70
+ }
71
+
72
+ // OneDrive/SharePoint shared links (delivered in 1:1 DMs when the user
73
+ // picks "Attach > OneDrive") cannot be fetched directly — the URL returns
74
+ // an HTML landing page rather than the file bytes. Rewrite them to the
75
+ // Graph shares endpoint so the auth fallback attaches a Graph-scoped token
76
+ // and the response is the real file content.
77
+ const sharesUrl = tryBuildGraphSharesUrlForSharedLink(contentUrl);
78
+ const resolvedUrl = sharesUrl ?? contentUrl;
79
+ // Graph shares returns raw bytes without a declared content type we can
80
+ // trust for routing — let the downloader infer MIME from the buffer.
81
+ const resolvedContentTypeHint = sharesUrl ? undefined : contentType;
82
+
83
+ return {
84
+ url: resolvedUrl,
85
+ fileHint: name || undefined,
86
+ contentTypeHint: resolvedContentTypeHint,
87
+ placeholder: inferPlaceholder({ contentType, fileName: name }),
88
+ };
89
+ }
90
+
91
+ function scopeCandidatesForUrl(url: string): string[] {
92
+ try {
93
+ const host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
94
+ const looksLikeGraph =
95
+ host.endsWith("graph.microsoft.com") ||
96
+ host.endsWith("sharepoint.com") ||
97
+ host.endsWith("1drv.ms") ||
98
+ host.includes("sharepoint");
99
+ return looksLikeGraph
100
+ ? ["https://graph.microsoft.com", "https://api.botframework.com"]
101
+ : ["https://api.botframework.com", "https://graph.microsoft.com"];
102
+ } catch {
103
+ return ["https://api.botframework.com", "https://graph.microsoft.com"];
104
+ }
105
+ }
106
+
107
+ function isRedirectStatus(status: number): boolean {
108
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
109
+ }
110
+
111
+ async function resolveInlineDataImageMime(inline: {
112
+ data: Buffer;
113
+ contentType?: string;
114
+ }): Promise<string | undefined> {
115
+ const detectedMime = await getMSTeamsRuntime().media.detectMime({
116
+ buffer: inline.data,
117
+ headerMime: inline.contentType,
118
+ });
119
+ const mime = normalizeOptionalLowercaseString(detectedMime ?? inline.contentType);
120
+ return mime?.startsWith("image/") ? mime : undefined;
121
+ }
122
+
123
+ async function fetchWithAuthFallback(params: {
124
+ url: string;
125
+ tokenProvider?: MSTeamsAccessTokenProvider;
126
+ fetchFn?: typeof fetch;
127
+ requestInit?: RequestInit;
128
+ resolveFn?: MSTeamsAttachmentResolveFn;
129
+ policy: MSTeamsAttachmentFetchPolicy;
130
+ }): Promise<Response> {
131
+ const firstAttempt = await safeFetchWithPolicy({
132
+ url: params.url,
133
+ policy: params.policy,
134
+ fetchFn: params.fetchFn,
135
+ requestInit: params.requestInit,
136
+ resolveFn: params.resolveFn,
137
+ });
138
+ if (firstAttempt.ok) {
139
+ return firstAttempt;
140
+ }
141
+ if (!params.tokenProvider) {
142
+ return firstAttempt;
143
+ }
144
+ if (firstAttempt.status !== 401 && firstAttempt.status !== 403) {
145
+ return firstAttempt;
146
+ }
147
+ if (!isUrlAllowed(params.url, params.policy.authAllowHosts)) {
148
+ return firstAttempt;
149
+ }
150
+
151
+ const scopes = scopeCandidatesForUrl(params.url);
152
+ const fetchFn = params.fetchFn ?? fetch;
153
+ for (const scope of scopes) {
154
+ try {
155
+ const token = await params.tokenProvider.getAccessToken(scope);
156
+ const authHeaders = new Headers(params.requestInit?.headers);
157
+ authHeaders.set("Authorization", `Bearer ${token}`);
158
+ const authAttempt = await safeFetchWithPolicy({
159
+ url: params.url,
160
+ policy: params.policy,
161
+ fetchFn,
162
+ requestInit: {
163
+ ...params.requestInit,
164
+ headers: authHeaders,
165
+ },
166
+ resolveFn: params.resolveFn,
167
+ });
168
+ if (authAttempt.ok) {
169
+ return authAttempt;
170
+ }
171
+ if (isRedirectStatus(authAttempt.status)) {
172
+ // Redirects in guarded fetch mode must propagate to the outer guard.
173
+ return authAttempt;
174
+ }
175
+ if (authAttempt.status !== 401 && authAttempt.status !== 403) {
176
+ // Preserve scope fallback semantics for non-auth failures.
177
+ continue;
178
+ }
179
+ } catch {
180
+ // Try the next scope.
181
+ }
182
+ }
183
+
184
+ return firstAttempt;
185
+ }
186
+
187
+ /**
188
+ * Download all file attachments from a Teams message (images, documents, etc.).
189
+ * Renamed from downloadMSTeamsImageAttachments to support all file types.
190
+ */
191
+ export async function downloadMSTeamsAttachments(params: {
192
+ attachments: MSTeamsAttachmentLike[] | undefined;
193
+ maxBytes: number;
194
+ tokenProvider?: MSTeamsAccessTokenProvider;
195
+ allowHosts?: string[];
196
+ authAllowHosts?: string[];
197
+ fetchFn?: typeof fetch;
198
+ resolveFn?: MSTeamsAttachmentResolveFn;
199
+ /** When true, embeds original filename in stored path for later extraction. */
200
+ preserveFilenames?: boolean;
201
+ /**
202
+ * Optional logger used to surface inline data decode failures and remote
203
+ * media download errors. Errors that are not logged here are invisible at
204
+ * INFO level and block diagnosis of issues like #63396.
205
+ */
206
+ logger?: MSTeamsAttachmentDownloadLogger;
207
+ }): Promise<MSTeamsInboundMedia[]> {
208
+ const list = Array.isArray(params.attachments) ? params.attachments : [];
209
+ if (list.length === 0) {
210
+ return [];
211
+ }
212
+ const policy = resolveAttachmentFetchPolicy({
213
+ allowHosts: params.allowHosts,
214
+ authAllowHosts: params.authAllowHosts,
215
+ });
216
+ const allowHosts = policy.allowHosts;
217
+ const ssrfPolicy = resolveMediaSsrfPolicy(allowHosts);
218
+
219
+ // Download ANY downloadable attachment (not just images)
220
+ const downloadable = list.filter(isDownloadableAttachment);
221
+ const candidates: DownloadCandidate[] = downloadable
222
+ .map(resolveDownloadCandidate)
223
+ .filter(Boolean) as DownloadCandidate[];
224
+
225
+ const inlineCandidates = extractInlineImageCandidates(list, {
226
+ maxInlineBytes: params.maxBytes,
227
+ maxInlineTotalBytes: params.maxBytes,
228
+ });
229
+
230
+ const seenUrls = new Set<string>();
231
+ for (const inline of inlineCandidates) {
232
+ if (inline.kind === "url") {
233
+ if (!isUrlAllowed(inline.url, allowHosts)) {
234
+ continue;
235
+ }
236
+ if (seenUrls.has(inline.url)) {
237
+ continue;
238
+ }
239
+ seenUrls.add(inline.url);
240
+ candidates.push({
241
+ url: inline.url,
242
+ fileHint: inline.fileHint,
243
+ contentTypeHint: inline.contentType,
244
+ placeholder: inline.placeholder,
245
+ });
246
+ }
247
+ }
248
+ if (candidates.length === 0 && inlineCandidates.length === 0) {
249
+ return [];
250
+ }
251
+
252
+ const out: MSTeamsInboundMedia[] = [];
253
+ for (const inline of inlineCandidates) {
254
+ if (inline.kind !== "data") {
255
+ continue;
256
+ }
257
+ if (inline.data.byteLength > params.maxBytes) {
258
+ continue;
259
+ }
260
+ try {
261
+ const contentType = await resolveInlineDataImageMime(inline);
262
+ if (!contentType) {
263
+ continue;
264
+ }
265
+ // Data inline candidates (base64 data URLs) don't have original filenames
266
+ const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(
267
+ inline.data,
268
+ contentType,
269
+ "inbound",
270
+ params.maxBytes,
271
+ );
272
+ out.push({
273
+ path: saved.path,
274
+ contentType: saved.contentType,
275
+ placeholder: inferPlaceholder({ contentType: saved.contentType ?? contentType }),
276
+ });
277
+ } catch (err) {
278
+ params.logger?.warn?.("msteams inline attachment decode failed", {
279
+ error: err instanceof Error ? err.message : String(err),
280
+ });
281
+ }
282
+ }
283
+ for (const candidate of candidates) {
284
+ if (!isUrlAllowed(candidate.url, allowHosts)) {
285
+ continue;
286
+ }
287
+ try {
288
+ const media = await downloadAndStoreMSTeamsRemoteMedia({
289
+ url: candidate.url,
290
+ filePathHint: candidate.fileHint ?? candidate.url,
291
+ maxBytes: params.maxBytes,
292
+ contentTypeHint: candidate.contentTypeHint,
293
+ placeholder: candidate.placeholder,
294
+ preserveFilenames: params.preserveFilenames,
295
+ ssrfPolicy,
296
+ // `fetchImpl` below already validates each hop against the hostname
297
+ // allowlist via `safeFetchWithPolicy`, so skip `readRemoteMediaBuffer`'s
298
+ // strict SSRF dispatcher (incompatible with Node 24+ / undici v7;
299
+ // see issue #63396).
300
+ useDirectFetch: true,
301
+ fetchImpl: (input, init) =>
302
+ fetchWithAuthFallback({
303
+ url: resolveRequestUrl(input),
304
+ tokenProvider: params.tokenProvider,
305
+ fetchFn: params.fetchFn,
306
+ requestInit: init,
307
+ resolveFn: params.resolveFn,
308
+ policy,
309
+ }),
310
+ });
311
+ out.push(media);
312
+ } catch (err) {
313
+ params.logger?.warn?.("msteams attachment download failed", {
314
+ error: err instanceof Error ? err.message : String(err),
315
+ host: safeHostForLog(candidate.url),
316
+ });
317
+ }
318
+ }
319
+ return out;
320
+ }
321
+
322
+ function safeHostForLog(url: string): string {
323
+ try {
324
+ return new URL(url).host;
325
+ } catch {
326
+ return "invalid-url";
327
+ }
328
+ }