@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,223 @@
1
+ /**
2
+ * FileConsentCard utilities for MS Teams large file uploads (>4MB) in personal chats.
3
+ *
4
+ * Teams requires user consent before the bot can upload large files. This module provides
5
+ * utilities for:
6
+ * - Building FileConsentCard attachments (to request upload permission)
7
+ * - Building FileInfoCard attachments (to confirm upload completion)
8
+ * - Parsing fileConsent/invoke activities
9
+ */
10
+
11
+ import { lookup } from "node:dns/promises";
12
+ import { isPrivateIpAddress } from "autobot/plugin-sdk/ssrf-policy";
13
+ import { normalizeLowercaseStringOrEmpty } from "autobot/plugin-sdk/string-coerce-runtime";
14
+ import { buildUserAgent } from "./user-agent.js";
15
+
16
+ /**
17
+ * Allowlist of domains that are valid targets for file consent uploads.
18
+ * These are the Microsoft/SharePoint domains that Teams legitimately provides
19
+ * as upload destinations in the FileConsentCard flow.
20
+ */
21
+ export const CONSENT_UPLOAD_HOST_ALLOWLIST = [
22
+ "sharepoint.com",
23
+ "sharepoint.us",
24
+ "sharepoint.de",
25
+ "sharepoint.cn",
26
+ "sharepoint-df.com",
27
+ "storage.live.com",
28
+ "onedrive.com",
29
+ "1drv.ms",
30
+ "graph.microsoft.com",
31
+ "graph.microsoft.us",
32
+ "graph.microsoft.de",
33
+ "graph.microsoft.cn",
34
+ ] as const;
35
+
36
+ /**
37
+ * Returns true if the given IPv4 or IPv6 address is private, internal, or
38
+ * special-use and must never be reached via consent uploads.
39
+ */
40
+ export const isPrivateOrReservedIP: (ip: string) => boolean = isPrivateIpAddress;
41
+
42
+ /**
43
+ * Validate that a consent upload URL is safe to PUT to.
44
+ * Checks:
45
+ * 1. Protocol is HTTPS
46
+ * 2. Hostname matches the consent upload allowlist
47
+ * 3. Resolved IP is not in a private/reserved range (anti-SSRF)
48
+ *
49
+ * @throws Error if the URL fails validation
50
+ */
51
+ export async function validateConsentUploadUrl(
52
+ url: string,
53
+ opts?: {
54
+ allowlist?: readonly string[];
55
+ resolveFn?: (hostname: string) => Promise<{ address: string } | { address: string }[]>;
56
+ },
57
+ ): Promise<void> {
58
+ let parsed: URL;
59
+ try {
60
+ parsed = new URL(url);
61
+ } catch {
62
+ throw new Error("Consent upload URL is not a valid URL");
63
+ }
64
+
65
+ // 1. Protocol check
66
+ if (parsed.protocol !== "https:") {
67
+ throw new Error(`Consent upload URL must use HTTPS, got ${parsed.protocol}`);
68
+ }
69
+
70
+ // 2. Hostname allowlist check
71
+ const hostname = normalizeLowercaseStringOrEmpty(parsed.hostname);
72
+ const allowlist = opts?.allowlist ?? CONSENT_UPLOAD_HOST_ALLOWLIST;
73
+ const hostAllowed = allowlist.some(
74
+ (entry) => hostname === entry || hostname.endsWith(`.${entry}`),
75
+ );
76
+ if (!hostAllowed) {
77
+ throw new Error(`Consent upload URL hostname "${hostname}" is not in the allowed domains`);
78
+ }
79
+
80
+ // 3. DNS resolution — reject private/reserved IPs.
81
+ // Check all resolved addresses to avoid SSRF bypass via mixed public/private answers.
82
+ const resolveFn = opts?.resolveFn ?? ((name: string) => lookup(name, { all: true }));
83
+ let resolved: { address: string }[];
84
+ try {
85
+ const result = await resolveFn(hostname);
86
+ resolved = Array.isArray(result) ? result : [result];
87
+ } catch {
88
+ throw new Error(`Failed to resolve consent upload URL hostname "${hostname}"`);
89
+ }
90
+
91
+ for (const entry of resolved) {
92
+ if (isPrivateOrReservedIP(entry.address)) {
93
+ throw new Error(`Consent upload URL resolves to a private/reserved IP (${entry.address})`);
94
+ }
95
+ }
96
+ }
97
+
98
+ interface FileConsentCardParams {
99
+ filename: string;
100
+ description?: string;
101
+ sizeInBytes: number;
102
+ /** Custom context data to include in the card (passed back in the invoke) */
103
+ context?: Record<string, unknown>;
104
+ }
105
+
106
+ interface FileInfoCardParams {
107
+ filename: string;
108
+ contentUrl: string;
109
+ uniqueId: string;
110
+ fileType: string;
111
+ }
112
+
113
+ /**
114
+ * Build a FileConsentCard attachment for requesting upload permission.
115
+ * Use this for files >= 4MB in personal (1:1) chats.
116
+ */
117
+ export function buildFileConsentCard(params: FileConsentCardParams) {
118
+ return {
119
+ contentType: "application/vnd.microsoft.teams.card.file.consent",
120
+ name: params.filename,
121
+ content: {
122
+ description: params.description ?? `File: ${params.filename}`,
123
+ sizeInBytes: params.sizeInBytes,
124
+ acceptContext: { filename: params.filename, ...params.context },
125
+ declineContext: { filename: params.filename, ...params.context },
126
+ },
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Build a FileInfoCard attachment for confirming upload completion.
132
+ * Send this after successfully uploading the file to the consent URL.
133
+ */
134
+ export function buildFileInfoCard(params: FileInfoCardParams) {
135
+ return {
136
+ contentType: "application/vnd.microsoft.teams.card.file.info",
137
+ contentUrl: params.contentUrl,
138
+ name: params.filename,
139
+ content: {
140
+ uniqueId: params.uniqueId,
141
+ fileType: params.fileType,
142
+ },
143
+ };
144
+ }
145
+
146
+ interface FileConsentUploadInfo {
147
+ name: string;
148
+ uploadUrl: string;
149
+ contentUrl: string;
150
+ uniqueId: string;
151
+ fileType: string;
152
+ }
153
+
154
+ interface FileConsentResponse {
155
+ action: "accept" | "decline";
156
+ uploadInfo?: FileConsentUploadInfo;
157
+ context?: Record<string, unknown>;
158
+ }
159
+
160
+ /**
161
+ * Parse a fileConsent/invoke activity.
162
+ * Returns null if the activity is not a file consent invoke.
163
+ */
164
+ export function parseFileConsentInvoke(activity: {
165
+ name?: string;
166
+ value?: unknown;
167
+ }): FileConsentResponse | null {
168
+ if (activity.name !== "fileConsent/invoke") {
169
+ return null;
170
+ }
171
+
172
+ const value = activity.value as {
173
+ type?: string;
174
+ action?: string;
175
+ uploadInfo?: FileConsentUploadInfo;
176
+ context?: Record<string, unknown>;
177
+ };
178
+
179
+ if (value?.type !== "fileUpload") {
180
+ return null;
181
+ }
182
+
183
+ return {
184
+ action: value.action === "accept" ? "accept" : "decline",
185
+ uploadInfo: value.uploadInfo,
186
+ context: value.context,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Upload a file to the consent URL provided by Teams.
192
+ * The URL is provided in the fileConsent/invoke response after user accepts.
193
+ *
194
+ * @throws Error if the URL fails SSRF validation (non-HTTPS, disallowed host, private IP)
195
+ */
196
+ export async function uploadToConsentUrl(params: {
197
+ url: string;
198
+ buffer: Buffer;
199
+ contentType?: string;
200
+ fetchFn?: typeof fetch;
201
+ /** Override for testing — custom allowlist and DNS resolver */
202
+ validationOpts?: {
203
+ allowlist?: readonly string[];
204
+ resolveFn?: (hostname: string) => Promise<{ address: string } | { address: string }[]>;
205
+ };
206
+ }): Promise<void> {
207
+ await validateConsentUploadUrl(params.url, params.validationOpts);
208
+
209
+ const fetchFn = params.fetchFn ?? fetch;
210
+ const res = await fetchFn(params.url, {
211
+ method: "PUT",
212
+ headers: {
213
+ "User-Agent": buildUserAgent(),
214
+ "Content-Type": params.contentType ?? "application/octet-stream",
215
+ "Content-Range": `bytes 0-${params.buffer.length - 1}/${params.buffer.length}`,
216
+ },
217
+ body: new Uint8Array(params.buffer),
218
+ });
219
+
220
+ if (!res.ok) {
221
+ throw new Error(`File upload to consent URL failed: ${res.status} ${res.statusText}`);
222
+ }
223
+ }
@@ -0,0 +1,36 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "autobot/plugin-sdk/string-coerce-runtime";
2
+ import type { DriveItemProperties } from "./graph-upload.js";
3
+
4
+ export function buildTeamsFileInfoCard(file: DriveItemProperties): {
5
+ contentType: string;
6
+ contentUrl: string;
7
+ name: string;
8
+ content: {
9
+ uniqueId: string;
10
+ fileType: string;
11
+ };
12
+ } {
13
+ // Extract unique ID from eTag (remove quotes, braces, and version suffix)
14
+ // Example eTag formats: "{GUID},version" or "\"{GUID},version\""
15
+ const rawETag = file.eTag;
16
+ const uniqueId =
17
+ rawETag
18
+ .replace(/^["']|["']$/g, "") // Remove outer quotes
19
+ .replace(/[{}]/g, "") // Remove curly braces
20
+ .split(",")[0] ?? rawETag; // Take the GUID part before comma
21
+
22
+ // Extract file extension from filename
23
+ const lastDot = file.name.lastIndexOf(".");
24
+ const fileType =
25
+ lastDot >= 0 ? normalizeLowercaseStringOrEmpty(file.name.slice(lastDot + 1)) : "";
26
+
27
+ return {
28
+ contentType: "application/vnd.microsoft.teams.card.file.info",
29
+ contentUrl: file.webDavUrl,
30
+ name: file.name,
31
+ content: {
32
+ uniqueId,
33
+ fileType,
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,168 @@
1
+ import type { AutoBotConfig } from "../runtime-api.js";
2
+ import { resolveConversationPath, resolveGraphConversationId } from "./graph-messages.js";
3
+ import {
4
+ deleteGraphRequest,
5
+ escapeOData,
6
+ fetchGraphJson,
7
+ patchGraphJson,
8
+ postGraphJson,
9
+ resolveGraphToken,
10
+ } from "./graph.js";
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Add Participant
14
+ // ---------------------------------------------------------------------------
15
+
16
+ type AddParticipantMSTeamsParams = {
17
+ cfg: AutoBotConfig;
18
+ to: string;
19
+ userId: string;
20
+ role?: string;
21
+ };
22
+
23
+ type AddParticipantMSTeamsResult = {
24
+ added: { userId: string; chatId: string };
25
+ };
26
+
27
+ type ConversationMemberRole = "member" | "owner";
28
+
29
+ function normalizeConversationMemberRole(role: string | undefined): ConversationMemberRole {
30
+ const normalized = role?.trim().toLowerCase() ?? "";
31
+ if (!normalized) {
32
+ return "member";
33
+ }
34
+ if (normalized === "member" || normalized === "owner") {
35
+ return normalized;
36
+ }
37
+ throw new Error('MS Teams participant role must be "member" or "owner".');
38
+ }
39
+
40
+ /**
41
+ * Add a user to a chat or channel via Graph API.
42
+ */
43
+ export async function addParticipantMSTeams(
44
+ params: AddParticipantMSTeamsParams,
45
+ ): Promise<AddParticipantMSTeamsResult> {
46
+ const token = await resolveGraphToken(params.cfg);
47
+ const conversationId = await resolveGraphConversationId(params.to);
48
+ const conv = resolveConversationPath(conversationId);
49
+
50
+ const body = {
51
+ "@odata.type": "#microsoft.graph.aadUserConversationMember",
52
+ roles: [normalizeConversationMemberRole(params.role)],
53
+ "user@odata.bind": `https://graph.microsoft.com/v1.0/users('${escapeOData(params.userId)}')`,
54
+ };
55
+
56
+ await postGraphJson<unknown>({
57
+ token,
58
+ path: `${conv.basePath}/members`,
59
+ body,
60
+ });
61
+
62
+ return { added: { userId: params.userId, chatId: conversationId } };
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Remove Participant
67
+ // ---------------------------------------------------------------------------
68
+
69
+ type RemoveParticipantMSTeamsParams = {
70
+ cfg: AutoBotConfig;
71
+ to: string;
72
+ userId: string;
73
+ };
74
+
75
+ type RemoveParticipantMSTeamsResult = {
76
+ removed: { userId: string; chatId: string };
77
+ };
78
+
79
+ type GraphConversationMember = {
80
+ id?: string;
81
+ userId?: string;
82
+ };
83
+
84
+ type GraphConversationMemberResponse = {
85
+ value?: GraphConversationMember[];
86
+ "@odata.nextLink"?: string;
87
+ };
88
+
89
+ /**
90
+ * Remove a user from a chat or channel via Graph API.
91
+ * Lists members first to resolve the membership ID, then deletes.
92
+ */
93
+ export async function removeParticipantMSTeams(
94
+ params: RemoveParticipantMSTeamsParams,
95
+ ): Promise<RemoveParticipantMSTeamsResult> {
96
+ const token = await resolveGraphToken(params.cfg);
97
+ const conversationId = await resolveGraphConversationId(params.to);
98
+ const conv = resolveConversationPath(conversationId);
99
+
100
+ // List members to find the membership ID for the target user. Graph can
101
+ // paginate large chats/channels, so walk `@odata.nextLink` before concluding
102
+ // the user is missing.
103
+ const MAX_PAGES = 10;
104
+ let nextPath: string | undefined = `${conv.basePath}/members`;
105
+ let page = 0;
106
+ let member: GraphConversationMember | undefined;
107
+ while (nextPath && page < MAX_PAGES && !member) {
108
+ const membersRes: GraphConversationMemberResponse =
109
+ await fetchGraphJson<GraphConversationMemberResponse>({
110
+ token,
111
+ path: nextPath,
112
+ });
113
+ member = (membersRes.value ?? []).find(
114
+ (candidate: GraphConversationMember) => candidate.userId === params.userId,
115
+ );
116
+ if (member) {
117
+ break;
118
+ }
119
+ const nextLink: string | undefined = membersRes["@odata.nextLink"];
120
+ nextPath = nextLink ? nextLink.replace("https://graph.microsoft.com/v1.0", "") : undefined;
121
+ page++;
122
+ }
123
+ if (!member?.id) {
124
+ throw new Error(`User ${params.userId} is not a member of this conversation`);
125
+ }
126
+
127
+ await deleteGraphRequest({
128
+ token,
129
+ path: `${conv.basePath}/members/${encodeURIComponent(member.id)}`,
130
+ });
131
+
132
+ return { removed: { userId: params.userId, chatId: conversationId } };
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Rename Group
137
+ // ---------------------------------------------------------------------------
138
+
139
+ type RenameGroupMSTeamsParams = {
140
+ cfg: AutoBotConfig;
141
+ to: string;
142
+ name: string;
143
+ };
144
+
145
+ type RenameGroupMSTeamsResult = {
146
+ renamed: { chatId: string; newName: string };
147
+ };
148
+
149
+ /**
150
+ * Rename a chat (topic) or channel (displayName) via Graph API.
151
+ */
152
+ export async function renameGroupMSTeams(
153
+ params: RenameGroupMSTeamsParams,
154
+ ): Promise<RenameGroupMSTeamsResult> {
155
+ const token = await resolveGraphToken(params.cfg);
156
+ const conversationId = await resolveGraphConversationId(params.to);
157
+ const conv = resolveConversationPath(conversationId);
158
+
159
+ const body = conv.kind === "chat" ? { topic: params.name } : { displayName: params.name };
160
+
161
+ await patchGraphJson<unknown>({
162
+ token,
163
+ path: conv.basePath,
164
+ body,
165
+ });
166
+
167
+ return { renamed: { chatId: conversationId, newName: params.name } };
168
+ }
@@ -0,0 +1,48 @@
1
+ import type { AutoBotConfig } from "../runtime-api.js";
2
+ import { fetchGraphJson, resolveGraphToken } from "./graph.js";
3
+
4
+ type GraphUserProfile = {
5
+ id?: string;
6
+ displayName?: string;
7
+ mail?: string;
8
+ jobTitle?: string;
9
+ userPrincipalName?: string;
10
+ officeLocation?: string;
11
+ };
12
+
13
+ type GetMemberInfoMSTeamsParams = {
14
+ cfg: AutoBotConfig;
15
+ userId: string;
16
+ };
17
+
18
+ type GetMemberInfoMSTeamsResult = {
19
+ user: {
20
+ id: string | undefined;
21
+ displayName: string | undefined;
22
+ mail: string | undefined;
23
+ jobTitle: string | undefined;
24
+ userPrincipalName: string | undefined;
25
+ officeLocation: string | undefined;
26
+ };
27
+ };
28
+
29
+ /**
30
+ * Fetch a user profile from Microsoft Graph by user ID.
31
+ */
32
+ export async function getMemberInfoMSTeams(
33
+ params: GetMemberInfoMSTeamsParams,
34
+ ): Promise<GetMemberInfoMSTeamsResult> {
35
+ const token = await resolveGraphToken(params.cfg);
36
+ const path = `/users/${encodeURIComponent(params.userId)}?$select=id,displayName,mail,jobTitle,userPrincipalName,officeLocation`;
37
+ const user = await fetchGraphJson<GraphUserProfile>({ token, path });
38
+ return {
39
+ user: {
40
+ id: user.id,
41
+ displayName: user.displayName,
42
+ mail: user.mail,
43
+ jobTitle: user.jobTitle,
44
+ userPrincipalName: user.userPrincipalName,
45
+ officeLocation: user.officeLocation,
46
+ },
47
+ };
48
+ }