@chrischall/microsoft-teams-mcp 0.3.0 → 0.4.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.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +279 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +42380 -37144
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +552 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +26 -6
- package/dist/model.js +499 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -0
- package/dist/token-cache.js +67 -0
- package/dist/tools/activity.js +155 -19
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/channels.js +60 -44
- package/dist/tools/chat.js +47 -42
- package/dist/tools/confirm.js +145 -0
- package/dist/tools/conversation.js +172 -32
- package/dist/tools/errors.js +18 -17
- package/dist/tools/healthcheck.js +86 -27
- package/dist/tools/limit.js +43 -12
- package/dist/tools/listing.js +116 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +162 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +63 -20
- package/package.json +1 -2
- package/server.json +80 -3
- package/skills/teams-fpx/SKILL.md +108 -92
- package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
- package/skills/teams-fpx/references/teams-env.sh +146 -0
- package/dist/client.js +0 -290
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
package/dist/model.js
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user's own notes chat ("notes to self") — the one `48:*` system
|
|
3
|
+
* conversation that is a real chat. Every other `48:*` id (calendar,
|
|
4
|
+
* notifications, …) is not one and is never listed.
|
|
5
|
+
*/
|
|
6
|
+
export const SELF_CHAT = '48:notes';
|
|
7
|
+
const SELF_CHAT_TITLE = 'Notes (self-chat)';
|
|
8
|
+
/** Names that resolve to {@link SELF_CHAT} outright, ahead of any substring match. */
|
|
9
|
+
export const SELF_CHAT_ALIASES = new Set(['notes', 'self']);
|
|
10
|
+
/**
|
|
11
|
+
* Message types a person wrote. Everything else is a system event that Teams
|
|
12
|
+
* never counts as unread: `RichText/Media_*` (call recordings, transcripts),
|
|
13
|
+
* `Event/*`, `ThreadActivity/*`, `Control/*`, ….
|
|
14
|
+
*/
|
|
15
|
+
const USER_MESSAGE_TYPES = new Set(['Text', 'RichText/Html']);
|
|
16
|
+
/** Longest last-message preview a conversation summary carries. */
|
|
17
|
+
const PREVIEW_CHARS = 200;
|
|
18
|
+
/** The preview of a last message that is a system event (a call, a member added, …). */
|
|
19
|
+
const SYSTEM_EVENT_PREVIEW = '(system event)';
|
|
20
|
+
/** An untopiced group chat's title when no one but the user is known to have written in it. */
|
|
21
|
+
export const UNTITLED_GROUP_TITLE = '(untitled group chat)';
|
|
22
|
+
/** An untopiced 1:1's title when the other person's name is not known. */
|
|
23
|
+
export const UNTITLED_ONE_ON_ONE_TITLE = '(1:1 chat)';
|
|
24
|
+
/** What an untopiced group chat's participant title starts with (see `tools/titles.ts`). */
|
|
25
|
+
export const GROUP_TITLE_PREFIX = 'Group chat: ';
|
|
26
|
+
/** A channel's team name when the team's own thread is listed but names nothing. */
|
|
27
|
+
const UNNAMED_TEAM = '(team)';
|
|
28
|
+
/** Inline images live on Skype's AMS object store; only those are attachment refs. */
|
|
29
|
+
const IMAGE_HOST_SUFFIX = '.asm.skype.com';
|
|
30
|
+
const IMAGE_OBJECT_PATH = /^\/v1\/objects\/([^/]+)\/views\//;
|
|
31
|
+
export function conversationKind(c) {
|
|
32
|
+
const id = c.id;
|
|
33
|
+
if (id === SELF_CHAT)
|
|
34
|
+
return 'self';
|
|
35
|
+
if (id.endsWith('@thread.tacv2'))
|
|
36
|
+
return 'channel';
|
|
37
|
+
const tp = c.threadProperties ?? {};
|
|
38
|
+
if (id.startsWith('19:meeting_') ||
|
|
39
|
+
/meeting/i.test(tp.productThreadType ?? '') ||
|
|
40
|
+
/meeting/i.test(tp.threadType ?? '')) {
|
|
41
|
+
return 'meeting';
|
|
42
|
+
}
|
|
43
|
+
if (id.endsWith('@unq.gbl.spaces'))
|
|
44
|
+
return 'oneOnOne';
|
|
45
|
+
return 'group';
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The arrival time (epoch ms) of the last message the user has read: the first
|
|
49
|
+
* segment of `consumptionhorizon` (`"<lastReadArrivalMs>;<clientMs>;<messageId>"`).
|
|
50
|
+
* 0 — everything unread — when absent or unparseable.
|
|
51
|
+
*/
|
|
52
|
+
export function readHorizon(c) {
|
|
53
|
+
const raw = c.properties?.consumptionhorizon;
|
|
54
|
+
if (typeof raw !== 'string')
|
|
55
|
+
return 0;
|
|
56
|
+
const n = Number(raw.split(';')[0]);
|
|
57
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
58
|
+
}
|
|
59
|
+
/** The sender's MRI (`8:orgid:<oid>`): `from` is a URL ending in it. */
|
|
60
|
+
export function senderMri(from) {
|
|
61
|
+
if (typeof from !== 'string' || from === '')
|
|
62
|
+
return undefined;
|
|
63
|
+
const mri = from.slice(from.lastIndexOf('/') + 1);
|
|
64
|
+
return mri === '' ? undefined : mri;
|
|
65
|
+
}
|
|
66
|
+
/** True for a message a person wrote, false for a system event. */
|
|
67
|
+
export function isUserMessage(m) {
|
|
68
|
+
return USER_MESSAGE_TYPES.has(m.messagetype ?? '');
|
|
69
|
+
}
|
|
70
|
+
function isDeleted(m) {
|
|
71
|
+
const t = m.properties?.deletetime;
|
|
72
|
+
return t !== undefined && t !== null && t !== '' && t !== 0;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Unread = arrived after the read horizon (a message id IS its arrival ms),
|
|
76
|
+
* written by someone other than the user, a real message, and not deleted.
|
|
77
|
+
*/
|
|
78
|
+
export function isUnread(m, horizon, meMri) {
|
|
79
|
+
const arrival = Number(m.id);
|
|
80
|
+
if (!Number.isFinite(arrival) || arrival <= horizon)
|
|
81
|
+
return false;
|
|
82
|
+
if (senderMri(m.from) === meMri)
|
|
83
|
+
return false;
|
|
84
|
+
return isUserMessage(m) && !isDeleted(m);
|
|
85
|
+
}
|
|
86
|
+
function toIso(value) {
|
|
87
|
+
if (typeof value !== 'string' || value === '')
|
|
88
|
+
return undefined;
|
|
89
|
+
const d = new Date(value);
|
|
90
|
+
return Number.isNaN(d.getTime()) ? undefined : d.toISOString();
|
|
91
|
+
}
|
|
92
|
+
function nonEmpty(s) {
|
|
93
|
+
const t = s?.trim();
|
|
94
|
+
return t ? t : undefined;
|
|
95
|
+
}
|
|
96
|
+
/** A team's thread: its own `spaceId`, or a `space` thread type. */
|
|
97
|
+
function isTeamThread(c) {
|
|
98
|
+
const tp = c.threadProperties ?? {};
|
|
99
|
+
return tp.spaceId === c.id || tp.threadType === 'space';
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A team's name from its own thread: the topic, else the space/topic-thread
|
|
103
|
+
* topic Teams sometimes carries instead, else {@link UNNAMED_TEAM}.
|
|
104
|
+
*/
|
|
105
|
+
function teamName(team) {
|
|
106
|
+
const tp = team.threadProperties ?? {};
|
|
107
|
+
return nonEmpty(tp.topic) ?? nonEmpty(tp.spaceThreadTopic) ?? nonEmpty(tp.topicThreadTopic) ?? UNNAMED_TEAM;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* `properties.lastimreceivedtime` as epoch ms. Despite the name it moves for
|
|
111
|
+
* system events too (a call recording sets it to that message's id), so it
|
|
112
|
+
* says only that SOMETHING arrived, not that a real message did. Seen as an ISO string; epoch ms (a number or a
|
|
113
|
+
* numeric string) is read too. `undefined` when absent or unparseable.
|
|
114
|
+
*/
|
|
115
|
+
export function lastImReceivedMs(c) {
|
|
116
|
+
const raw = c.properties?.lastimreceivedtime;
|
|
117
|
+
let ms;
|
|
118
|
+
if (typeof raw === 'number')
|
|
119
|
+
ms = raw;
|
|
120
|
+
else if (typeof raw === 'string' && /^\s*\d+\s*$/.test(raw))
|
|
121
|
+
ms = Number(raw);
|
|
122
|
+
else if (typeof raw === 'string' && raw.trim() !== '')
|
|
123
|
+
ms = Date.parse(raw);
|
|
124
|
+
else
|
|
125
|
+
return undefined;
|
|
126
|
+
return Number.isFinite(ms) && ms > 0 ? ms : undefined;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* The conversation's newest activity of any kind (epoch ms): the later of the
|
|
130
|
+
* last message's arrival (its id) and `lastimreceivedtime`, since either can
|
|
131
|
+
* lag the other. `undefined` when the listing carries neither. Nothing real
|
|
132
|
+
* can be unread after this, so it bounds how recent an unread message can be.
|
|
133
|
+
*/
|
|
134
|
+
export function newestActivityMs(c) {
|
|
135
|
+
const lastArrival = c.lastMessage !== undefined ? Number(c.lastMessage.id) : NaN;
|
|
136
|
+
const signals = [lastArrival, lastImReceivedMs(c)].filter((n) => n !== undefined && Number.isFinite(n) && n > 0);
|
|
137
|
+
return signals.length === 0 ? undefined : Math.max(...signals);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Whether the conversation is an unread CANDIDATE: its newest activity — the
|
|
141
|
+
* later of `lastimreceivedtime` and the last message's arrival, of any type —
|
|
142
|
+
* is past the read horizon (0 for a conversation never opened), and is not
|
|
143
|
+
* the user's own doing.
|
|
144
|
+
*
|
|
145
|
+
* Only a candidate. Measured live (2026-10-10): `lastimreceivedtime` equals
|
|
146
|
+
* the last message's id even when that is a call recording, and `lastMessage`
|
|
147
|
+
* can be stale (older than system events after it), so neither can say a real
|
|
148
|
+
* message is waiting. The tools confirm a candidate by reading the messages
|
|
149
|
+
* past the horizon. A false here is reliable: nothing at all came after the
|
|
150
|
+
* horizon, or the newest thing is the user's own message.
|
|
151
|
+
*/
|
|
152
|
+
export function isUnreadCandidate(c, meMri) {
|
|
153
|
+
const horizon = readHorizon(c);
|
|
154
|
+
const last = c.lastMessage;
|
|
155
|
+
const lastArrival = last !== undefined ? Number(last.id) : NaN;
|
|
156
|
+
const newest = newestActivityMs(c);
|
|
157
|
+
if (newest === undefined || newest <= horizon)
|
|
158
|
+
return false;
|
|
159
|
+
// The newest thing is the user's own doing: they were there for it.
|
|
160
|
+
const lastIsMine = last !== undefined && senderMri(last.from) === meMri;
|
|
161
|
+
return !(lastIsMine && lastArrival >= newest);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The other person's MRI in a 1:1: its id is `19:<oid>_<oid>@unq.gbl.spaces`,
|
|
165
|
+
* the two people's AAD object ids, so the one that is not the user's is
|
|
166
|
+
* theirs (`8:orgid:<oid>`). `undefined` when the id is not shaped so or does
|
|
167
|
+
* not name the user — then the listing cannot say who the other person is.
|
|
168
|
+
*/
|
|
169
|
+
export function oneOnOnePeerMri(id, meMri) {
|
|
170
|
+
const m = /^19:([^_@]+)_([^_@]+)@unq\.gbl\.spaces$/.exec(id);
|
|
171
|
+
const prefix = '8:orgid:';
|
|
172
|
+
if (m === null || !meMri.startsWith(prefix))
|
|
173
|
+
return undefined;
|
|
174
|
+
const mine = meMri.slice(prefix.length).toLowerCase();
|
|
175
|
+
const [a, b] = [m[1], m[2]];
|
|
176
|
+
if (a.toLowerCase() === mine && b.toLowerCase() !== mine)
|
|
177
|
+
return `${prefix}${b}`;
|
|
178
|
+
if (b.toLowerCase() === mine && a.toLowerCase() !== mine)
|
|
179
|
+
return `${prefix}${a}`;
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
/** True when the sender's MRI is `mri`, ignoring case (oids are GUIDs). */
|
|
183
|
+
export function isFromMri(from, mri) {
|
|
184
|
+
return senderMri(from)?.toLowerCase() === mri.toLowerCase();
|
|
185
|
+
}
|
|
186
|
+
/** A `properties` flag Teams sends as `"true"` / `"True"` (or, defensively, a boolean). */
|
|
187
|
+
function flag(c, name) {
|
|
188
|
+
const v = c.properties?.[name];
|
|
189
|
+
return v === true || (typeof v === 'string' && v.trim().toLowerCase() === 'true');
|
|
190
|
+
}
|
|
191
|
+
/** A channel the user has hidden in Teams. */
|
|
192
|
+
function isHiddenChannel(c) {
|
|
193
|
+
return c.memberProperties?.interest === 'NotInterested';
|
|
194
|
+
}
|
|
195
|
+
export function conversationSummary(c, meMri, all = []) {
|
|
196
|
+
const kind = conversationKind(c);
|
|
197
|
+
const tp = c.threadProperties ?? {};
|
|
198
|
+
const last = c.lastMessage;
|
|
199
|
+
const systemEvent = last !== undefined && !isUserMessage(last);
|
|
200
|
+
const lastFromMe = last !== undefined && senderMri(last.from) === meMri;
|
|
201
|
+
// A system event's display name is whoever triggered it, not a sender.
|
|
202
|
+
const lastSender = systemEvent ? undefined : nonEmpty(last?.imdisplayname);
|
|
203
|
+
const ownTeam = kind === 'channel' && isTeamThread(c);
|
|
204
|
+
let title = kind === 'self' ? SELF_CHAT_TITLE : ownTeam ? 'General' : nonEmpty(tp.topic);
|
|
205
|
+
let participants;
|
|
206
|
+
if (title === undefined && kind === 'oneOnOne') {
|
|
207
|
+
// A 1:1 is named after the other person, whom its id names. The listing
|
|
208
|
+
// knows their name only when they sent the last message; otherwise
|
|
209
|
+
// `tools/titles.ts` finds it in their recent messages.
|
|
210
|
+
const peer = oneOnOnePeerMri(c.id, meMri);
|
|
211
|
+
const fromPeer = peer !== undefined ? last !== undefined && isFromMri(last.from, peer) : !lastFromMe;
|
|
212
|
+
const name = fromPeer ? lastSender : undefined;
|
|
213
|
+
title = name ?? UNTITLED_ONE_ON_ONE_TITLE;
|
|
214
|
+
if (name !== undefined)
|
|
215
|
+
participants = [name];
|
|
216
|
+
}
|
|
217
|
+
else if (title === undefined) {
|
|
218
|
+
// An untopiced group chat's last sender is only a stand-in: `tools/titles.ts`
|
|
219
|
+
// names it after its recent participants instead.
|
|
220
|
+
const untitled = kind === 'group' ? UNTITLED_GROUP_TITLE : '(untitled chat)';
|
|
221
|
+
title = kind === 'channel' ? 'General' : (!lastFromMe ? lastSender : undefined) ?? untitled;
|
|
222
|
+
}
|
|
223
|
+
let team;
|
|
224
|
+
if (kind === 'channel') {
|
|
225
|
+
const teamThread = ownTeam ? c : tp.spaceId ? all.find((x) => x.id === tp.spaceId) : undefined;
|
|
226
|
+
if (teamThread !== undefined)
|
|
227
|
+
team = teamName(teamThread);
|
|
228
|
+
}
|
|
229
|
+
const lastActivity = last ? (toIso(last.originalarrivaltime) ?? toIso(last.composetime)) : undefined;
|
|
230
|
+
const preview = systemEvent ? SYSTEM_EVENT_PREVIEW : last?.content !== undefined ? htmlToText(last.content) : undefined;
|
|
231
|
+
const unread = isUnreadCandidate(c, meMri);
|
|
232
|
+
const hidden = kind === 'channel' && isHiddenChannel(c);
|
|
233
|
+
return {
|
|
234
|
+
id: c.id,
|
|
235
|
+
kind,
|
|
236
|
+
title,
|
|
237
|
+
...(team !== undefined ? { team } : {}),
|
|
238
|
+
unread,
|
|
239
|
+
unread_confirmed: false,
|
|
240
|
+
...(hidden ? { hidden: true } : {}),
|
|
241
|
+
...(flag(c, 'favorite') ? { favorite: true } : {}),
|
|
242
|
+
...(flag(c, 'ispinned') ? { pinned: true } : {}),
|
|
243
|
+
...(lastActivity !== undefined ? { lastActivity } : {}),
|
|
244
|
+
...(preview ? { lastMessagePreview: truncate(preview, PREVIEW_CHARS) } : {}),
|
|
245
|
+
...(lastSender !== undefined ? { lastSender } : {}),
|
|
246
|
+
...(participants !== undefined ? { participants } : {}),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function truncate(s, max) {
|
|
250
|
+
return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
|
|
251
|
+
}
|
|
252
|
+
/*
|
|
253
|
+
* Placeholders that survive tag-stripping, so blockquote depth can be applied
|
|
254
|
+
* after the text is decoded. Control characters never come out of entity
|
|
255
|
+
* decoding (it drops them), so a message cannot forge one.
|
|
256
|
+
*/
|
|
257
|
+
const QUOTE_OPEN = '\u0001';
|
|
258
|
+
const QUOTE_CLOSE = '\u0002';
|
|
259
|
+
const NAMED_ENTITIES = {
|
|
260
|
+
amp: '&',
|
|
261
|
+
lt: '<',
|
|
262
|
+
gt: '>',
|
|
263
|
+
quot: '"',
|
|
264
|
+
apos: "'",
|
|
265
|
+
nbsp: ' ',
|
|
266
|
+
};
|
|
267
|
+
function decodeEntities(s) {
|
|
268
|
+
// One pass, so `&lt;` becomes `<` and not `<`.
|
|
269
|
+
return s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
|
|
270
|
+
if (name !== undefined)
|
|
271
|
+
return NAMED_ENTITIES[name.toLowerCase()] ?? whole;
|
|
272
|
+
const code = dec !== undefined ? Number(dec) : parseInt(hex, 16);
|
|
273
|
+
if (!Number.isFinite(code) || code > 0x10ffff)
|
|
274
|
+
return whole;
|
|
275
|
+
// Drop control characters (keeping tab/newline): they carry no text and
|
|
276
|
+
// would collide with the quote placeholders.
|
|
277
|
+
if (code < 0x20 && code !== 0x09 && code !== 0x0a)
|
|
278
|
+
return '';
|
|
279
|
+
return String.fromCodePoint(code);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
function attr(tag, name) {
|
|
283
|
+
const m = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(tag);
|
|
284
|
+
return m ? (m[1] ?? m[2]) : undefined;
|
|
285
|
+
}
|
|
286
|
+
const stripTags = (s) => s.replace(/<\/?[a-z!][^>]*>/gi, '');
|
|
287
|
+
/**
|
|
288
|
+
* A Teams message body as readable plain text. Links keep their target as
|
|
289
|
+
* `text (url)`, inline images become `[image]` (emoji become their alt text),
|
|
290
|
+
* and a quoted reply's lines are prefixed `> `. No HTML library: Teams bodies
|
|
291
|
+
* are a small, regular subset.
|
|
292
|
+
*/
|
|
293
|
+
export function htmlToText(html) {
|
|
294
|
+
let s = html.replace(/[\u0001\u0002]/g, '');
|
|
295
|
+
s = s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, '');
|
|
296
|
+
s = s.replace(/<blockquote\b[^>]*>/gi, `\n${QUOTE_OPEN}\n`).replace(/<\/blockquote\s*>/gi, `\n${QUOTE_CLOSE}\n`);
|
|
297
|
+
s = s.replace(/<img\b[^>]*>/gi, (tag) => {
|
|
298
|
+
const alt = attr(tag, 'alt');
|
|
299
|
+
return /schema\.skype\.com\/Emoji/i.test(attr(tag, 'itemtype') ?? '') && alt ? alt : '[image]';
|
|
300
|
+
});
|
|
301
|
+
s = s.replace(/<a\b([^>]*)>([\s\S]*?)<\/a\s*>/gi, (_whole, attrs, inner) => {
|
|
302
|
+
const href = attr(` ${attrs}`, 'href');
|
|
303
|
+
const label = stripTags(inner).trim();
|
|
304
|
+
if (!href)
|
|
305
|
+
return inner;
|
|
306
|
+
if (label === '' || label === href)
|
|
307
|
+
return href;
|
|
308
|
+
return `${inner} (${href})`;
|
|
309
|
+
});
|
|
310
|
+
// Block elements start and end a line (a quote's author <strong> runs
|
|
311
|
+
// straight into its <p> otherwise); the blank lines this makes collapse below.
|
|
312
|
+
s = s.replace(/<br\s*\/?>/gi, '\n').replace(/<\/?(p|div|li|tr|h[1-6])\b[^>]*>/gi, '\n');
|
|
313
|
+
s = decodeEntities(stripTags(s));
|
|
314
|
+
const out = [];
|
|
315
|
+
let depth = 0;
|
|
316
|
+
for (const raw of s.split(/\r?\n/)) {
|
|
317
|
+
const line = raw.replace(/[ \t ]+/g, ' ').trim();
|
|
318
|
+
if (line === QUOTE_OPEN)
|
|
319
|
+
depth++;
|
|
320
|
+
else if (line === QUOTE_CLOSE)
|
|
321
|
+
depth = Math.max(0, depth - 1);
|
|
322
|
+
else if (line !== '')
|
|
323
|
+
out.push(`${'> '.repeat(depth)}${line}`);
|
|
324
|
+
}
|
|
325
|
+
return out.join('\n');
|
|
326
|
+
}
|
|
327
|
+
function fileAttachments(raw) {
|
|
328
|
+
let parsed = raw;
|
|
329
|
+
if (typeof raw === 'string') {
|
|
330
|
+
try {
|
|
331
|
+
parsed = JSON.parse(raw);
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
return [];
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (!Array.isArray(parsed))
|
|
338
|
+
return [];
|
|
339
|
+
const out = [];
|
|
340
|
+
for (const f of parsed) {
|
|
341
|
+
if (f === null || typeof f !== 'object')
|
|
342
|
+
continue;
|
|
343
|
+
const o = f;
|
|
344
|
+
const info = (o.fileInfo && typeof o.fileInfo === 'object' ? o.fileInfo : {});
|
|
345
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
|
|
346
|
+
const name = str(o.fileName) ?? str(o.title) ?? '(file)';
|
|
347
|
+
const type = str(o.fileType) ?? str(o.type);
|
|
348
|
+
const openUrl = str(o.openUrl) ?? str(info.shareUrl);
|
|
349
|
+
const url = str(o.objectUrl) ?? str(info.fileUrl);
|
|
350
|
+
out.push({
|
|
351
|
+
name,
|
|
352
|
+
...(type !== undefined ? { type } : {}),
|
|
353
|
+
...(openUrl !== undefined ? { openUrl } : {}),
|
|
354
|
+
...(url !== undefined ? { url } : {}),
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
function imageAttachments(html) {
|
|
360
|
+
const out = [];
|
|
361
|
+
const seen = new Set();
|
|
362
|
+
for (const [tag] of html.matchAll(/<img\b[^>]*>/gi)) {
|
|
363
|
+
const src = attr(tag, 'src');
|
|
364
|
+
if (!src)
|
|
365
|
+
continue;
|
|
366
|
+
let u;
|
|
367
|
+
try {
|
|
368
|
+
u = new URL(decodeEntities(src));
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (u.protocol !== 'https:' || !u.hostname.endsWith(IMAGE_HOST_SUFFIX))
|
|
374
|
+
continue;
|
|
375
|
+
const ref = IMAGE_OBJECT_PATH.exec(u.pathname)?.[1];
|
|
376
|
+
if (!ref || seen.has(ref))
|
|
377
|
+
continue;
|
|
378
|
+
seen.add(ref);
|
|
379
|
+
out.push({ ref, url: u.toString() });
|
|
380
|
+
}
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* `properties.emotions`: a JSON string (or, sometimes, an already-parsed
|
|
385
|
+
* array) of `{ key, users: [{ mri, time }] }`. Keys nobody holds any more are
|
|
386
|
+
* dropped; anything unreadable yields no reactions rather than an error.
|
|
387
|
+
*/
|
|
388
|
+
function reactionsOf(raw, meMri) {
|
|
389
|
+
let parsed = raw;
|
|
390
|
+
if (typeof raw === 'string') {
|
|
391
|
+
try {
|
|
392
|
+
parsed = JSON.parse(raw);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return [];
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (!Array.isArray(parsed))
|
|
399
|
+
return [];
|
|
400
|
+
const out = [];
|
|
401
|
+
for (const e of parsed) {
|
|
402
|
+
if (e === null || typeof e !== 'object')
|
|
403
|
+
continue;
|
|
404
|
+
const { key, users } = e;
|
|
405
|
+
if (typeof key !== 'string' || key === '' || !Array.isArray(users) || users.length === 0)
|
|
406
|
+
continue;
|
|
407
|
+
const byMe = users.some((u) => u?.mri === meMri);
|
|
408
|
+
out.push({ key, count: users.length, byMe });
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Messages oldest first, by arrival (a message id IS its arrival ms).
|
|
414
|
+
*
|
|
415
|
+
* The service pages newest first but does not strictly order within a page:
|
|
416
|
+
* live, a quote-reply sent 6s after its original came back ahead of it, so a
|
|
417
|
+
* plain reverse() listed the reply first. Ids that are not numbers sort by
|
|
418
|
+
* originalarrivaltime instead, and keep their page order when that is missing.
|
|
419
|
+
*/
|
|
420
|
+
export function oldestFirst(messages) {
|
|
421
|
+
const at = (m) => {
|
|
422
|
+
const id = Number(m.id);
|
|
423
|
+
if (Number.isFinite(id))
|
|
424
|
+
return id;
|
|
425
|
+
const t = Date.parse(m.originalarrivaltime ?? '');
|
|
426
|
+
return Number.isNaN(t) ? Number.NaN : t;
|
|
427
|
+
};
|
|
428
|
+
return messages
|
|
429
|
+
.map((m, i) => ({ m, i, t: at(m) }))
|
|
430
|
+
.reverse()
|
|
431
|
+
.sort((a, b) => (Number.isNaN(a.t) || Number.isNaN(b.t) ? 0 : a.t - b.t))
|
|
432
|
+
.map(({ m }) => m);
|
|
433
|
+
}
|
|
434
|
+
export function normaliseMessage(m, meMri) {
|
|
435
|
+
const props = m.properties ?? {};
|
|
436
|
+
const mri = senderMri(m.from);
|
|
437
|
+
const arrival = Number(m.id);
|
|
438
|
+
const time = toIso(m.originalarrivaltime) ??
|
|
439
|
+
toIso(m.composetime) ??
|
|
440
|
+
(Number.isFinite(arrival) ? new Date(arrival).toISOString() : '');
|
|
441
|
+
const subject = typeof props.subject === 'string' ? nonEmpty(props.subject) : undefined;
|
|
442
|
+
const root = /;messageid=(\d+)/.exec(m.conversationLink ?? '')?.[1];
|
|
443
|
+
const content = m.content ?? '';
|
|
444
|
+
const reactions = reactionsOf(props.emotions, meMri);
|
|
445
|
+
return {
|
|
446
|
+
id: m.id,
|
|
447
|
+
time,
|
|
448
|
+
sender: nonEmpty(m.imdisplayname) ?? mri ?? 'unknown',
|
|
449
|
+
fromMe: mri !== undefined && mri === meMri,
|
|
450
|
+
text: htmlToText(content),
|
|
451
|
+
...(subject !== undefined ? { subject } : {}),
|
|
452
|
+
...(root !== undefined && root !== m.id ? { replyTo: root } : {}),
|
|
453
|
+
edited: props.edittime !== undefined && props.edittime !== null && props.edittime !== '',
|
|
454
|
+
...(isDeleted(m) ? { deleted: true } : {}),
|
|
455
|
+
attachments: { files: fileAttachments(props.files), images: imageAttachments(content) },
|
|
456
|
+
...(reactions.length > 0 ? { reactions } : {}),
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Every conversation's summary, with the self-chat added when the listing did
|
|
461
|
+
* not carry it — so `48:notes` resolves by id or name whether or not Teams
|
|
462
|
+
* listed it.
|
|
463
|
+
*/
|
|
464
|
+
export function summariseAll(raw, meMri) {
|
|
465
|
+
const out = raw.map((c) => conversationSummary(c, meMri, raw));
|
|
466
|
+
if (!out.some((s) => s.id === SELF_CHAT))
|
|
467
|
+
out.push(conversationSummary({ id: SELF_CHAT }, meMri));
|
|
468
|
+
return out;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Resolve a user's `conversation` argument: an exact id wins outright, then
|
|
472
|
+
* `notes` / `self` name the self-chat, else a case-insensitive substring of
|
|
473
|
+
* the title, team name, or one of an untitled group chat's participants. A
|
|
474
|
+
* title this server made up — "Group chat: …" or "(untitled group chat)" — is
|
|
475
|
+
* not itself matched, so "group" or "chat" does not hit every untitled group
|
|
476
|
+
* chat: such a chat matches by its participants instead.
|
|
477
|
+
*/
|
|
478
|
+
export function matchConversations(summaries, query) {
|
|
479
|
+
const exact = summaries.find((s) => s.id === query);
|
|
480
|
+
if (exact)
|
|
481
|
+
return [exact];
|
|
482
|
+
const q = query.trim().toLowerCase();
|
|
483
|
+
if (q === '')
|
|
484
|
+
return [];
|
|
485
|
+
if (SELF_CHAT_ALIASES.has(q)) {
|
|
486
|
+
const self = summaries.find((s) => s.id === SELF_CHAT);
|
|
487
|
+
if (self)
|
|
488
|
+
return [self];
|
|
489
|
+
}
|
|
490
|
+
return summaries.filter((s) => (hasRealTitle(s) && s.title.toLowerCase().includes(q)) ||
|
|
491
|
+
(s.team?.toLowerCase().includes(q) ?? false) ||
|
|
492
|
+
(s.participants?.some((p) => p.toLowerCase().includes(q)) ?? false));
|
|
493
|
+
}
|
|
494
|
+
/** False for a title made from participants, or an untitled-group / untitled-1:1 stand-in. */
|
|
495
|
+
function hasRealTitle(s) {
|
|
496
|
+
if (s.title === UNTITLED_GROUP_TITLE || s.title === UNTITLED_ONE_ON_ONE_TITLE)
|
|
497
|
+
return false;
|
|
498
|
+
return !(s.participants !== undefined && s.title.startsWith(GROUP_TITLE_PREFIX));
|
|
499
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bootstrap-only fetchproxy auth for SharePoint shared-file download.
|
|
3
|
+
*
|
|
4
|
+
* A shared file in a Teams chat lives in SharePoint, not the Teams AMS object
|
|
5
|
+
* store that holds inline images, so downloading its contents needs a
|
|
6
|
+
* SharePoint token — NOT the chat-service token `auth-fetchproxy.ts` captures.
|
|
7
|
+
* The token is captured from the user's OneDrive host
|
|
8
|
+
* (`{tenant}-my.sharepoint.com`): the browser authenticates that host during
|
|
9
|
+
* normal Teams use and its token reads team-site files too, whereas it never
|
|
10
|
+
* issues a capturable request to a tenant-root team-site host. The caller
|
|
11
|
+
* resolves this capture host from the file's host via `captureHostFor` and
|
|
12
|
+
* passes it as `host` here. We snapshot the `Authorization: Bearer …` header off
|
|
13
|
+
* a request to it, then talk to the SharePoint v2.1 shares API with a plain Node
|
|
14
|
+
* `fetch`.
|
|
15
|
+
*
|
|
16
|
+
* Verified live 2026-10-11 against a real Teams tenant:
|
|
17
|
+
* - the working token has `aud` = the SharePoint/Office 365 resource GUID
|
|
18
|
+
* (`00000003-0000-0ff1-ce00-000000000000`), not the chat service's — the
|
|
19
|
+
* chatsvc token returns 401 on SharePoint, and Graph `/shares` returns 403;
|
|
20
|
+
* - that token authenticates a plain server-side GET of
|
|
21
|
+
* `/_api/v2.1/shares/u!{base64url(objectUrl)}/driveItem`, whose
|
|
22
|
+
* `@content.downloadUrl` is a pre-signed link fetched with no auth;
|
|
23
|
+
* - it is short-lived (~53 min) and host-family-scoped: the
|
|
24
|
+
* `{tenant}-my.sharepoint.com` OneDrive token also worked on
|
|
25
|
+
* `{tenant}.sharepoint.com`, but got 403 on a separate OneDrive-region host
|
|
26
|
+
* — so that region needs its own captured token.
|
|
27
|
+
*
|
|
28
|
+
* The capture layer cannot wildcard the host: `validateCaptureHeaderDecls` runs
|
|
29
|
+
* each capture host through `HOSTNAME_RE`, which rejects `*.sharepoint.com`. The
|
|
30
|
+
* capture host is therefore a concrete OneDrive host, resolved from the file's
|
|
31
|
+
* host by `captureHostFor` at download time.
|
|
32
|
+
* The pairing TRUST SCOPE may still be the broad `sharepoint.com` —
|
|
33
|
+
* `hostMatchesAnyDomain` accepts any `*.sharepoint.com` subdomain via
|
|
34
|
+
* `endsWith('.' + domain)` — so one domain covers every tenant SP host without
|
|
35
|
+
* re-pairing per host.
|
|
36
|
+
*
|
|
37
|
+
* Import this module LAZILY (`await import('./sharepoint-auth.js')`) from the
|
|
38
|
+
* code that needs a token, as `auth-fetchproxy.ts` is, so a server run with
|
|
39
|
+
* `TEAMS_DISABLE_FETCHPROXY` never has to load the bridge to boot.
|
|
40
|
+
*/
|
|
41
|
+
import { createBootstrapOpts, createFetchproxyTransport } from '@chrischall/mcp-utils/fetchproxy';
|
|
42
|
+
import { bridgeDeadlineMs, captureWindowMs } from './capture-window.js';
|
|
43
|
+
import { getWsPort, stripBearer } from './auth-fetchproxy.js';
|
|
44
|
+
import { PACKAGE_NAME, VERSION } from './version.js';
|
|
45
|
+
/**
|
|
46
|
+
* The extension's trust boundary for the SharePoint path: the broad family
|
|
47
|
+
* domain. `hostMatchesAnyDomain` treats this as "any `*.sharepoint.com`", so a
|
|
48
|
+
* single paired domain covers every tenant SP host, while the per-host capture
|
|
49
|
+
* decl below stays a concrete hostname (the capture layer rejects a wildcard).
|
|
50
|
+
*/
|
|
51
|
+
export const SHAREPOINT_TRUST_DOMAINS = ['sharepoint.com'];
|
|
52
|
+
/**
|
|
53
|
+
* True for a concrete SharePoint tenant host (`{label}.sharepoint.com`), such
|
|
54
|
+
* as `transunion-my.sharepoint.com` or `transunion.sharepoint.com`. Rejects a
|
|
55
|
+
* bare `sharepoint.com`, a suffix spoof (`sharepoint.com.evil.com`), and any
|
|
56
|
+
* non-SharePoint host. Host is lowercased before matching.
|
|
57
|
+
*/
|
|
58
|
+
export function isSharePointHost(host) {
|
|
59
|
+
return /^[a-z0-9][a-z0-9-]*\.sharepoint\.com$/.test(host.toLowerCase());
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The host to capture a SharePoint token FROM, for a file that lives on
|
|
63
|
+
* `fileHost`.
|
|
64
|
+
*
|
|
65
|
+
* Verified live 2026-10-11: the browser authenticates the user's OneDrive host
|
|
66
|
+
* (`<tenant>-my.sharepoint.com`) during normal Teams use, but never issues a
|
|
67
|
+
* capturable page request to a tenant-root team-site host
|
|
68
|
+
* (`<tenant>.sharepoint.com`) — so capturing from the file's own host times out
|
|
69
|
+
* for a team-site file. The `-my` token, however, downloads team-site files too
|
|
70
|
+
* (it worked cross-host to `transunion.sharepoint.com` in the spike). So:
|
|
71
|
+
* - a file already on a `*-my` host → capture from that host (incl. a separate
|
|
72
|
+
* region OneDrive like `<tenant>ind-my`, which needs its own token);
|
|
73
|
+
* - a file on a `<tenant>.sharepoint.com` root → capture from `<tenant>-my`.
|
|
74
|
+
* The result always satisfies {@link isSharePointHost}. One `-my` token thus
|
|
75
|
+
* serves every file on both that OneDrive and its tenant root, which is why the
|
|
76
|
+
* client keys its per-host token cache by this capture host.
|
|
77
|
+
*/
|
|
78
|
+
export function captureHostFor(fileHost) {
|
|
79
|
+
const h = fileHost.toLowerCase();
|
|
80
|
+
if (/-my\.sharepoint\.com$/.test(h))
|
|
81
|
+
return h;
|
|
82
|
+
const m = /^([a-z0-9][a-z0-9-]*)\.sharepoint\.com$/.exec(h);
|
|
83
|
+
return m ? `${m[1]}-my.sharepoint.com` : h;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Shortest plausible token. Real ones are several KB of JWT; this only guards
|
|
87
|
+
* against an empty or echoed header, not against a wrong-audience token.
|
|
88
|
+
*/
|
|
89
|
+
const MIN_TOKEN_LENGTH = 100;
|
|
90
|
+
/**
|
|
91
|
+
* Capture a SharePoint access token for `host` from the user's signed-in Teams
|
|
92
|
+
* tab. Returns the bare token (no `Bearer ` prefix).
|
|
93
|
+
*
|
|
94
|
+
* `host` must be a concrete SharePoint host — it becomes the capture decl, and
|
|
95
|
+
* sending a bearer later depends on it being one we vetted.
|
|
96
|
+
*/
|
|
97
|
+
export async function captureSharePointTokenViaFetchproxy(host, env = process.env) {
|
|
98
|
+
if (!isSharePointHost(host)) {
|
|
99
|
+
throw new Error(`refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a ` +
|
|
100
|
+
'*.sharepoint.com host');
|
|
101
|
+
}
|
|
102
|
+
// The one request we capture from: any call the browser makes to this
|
|
103
|
+
// OneDrive host (the caller resolves it from the file's host via
|
|
104
|
+
// `captureHostFor`). A concrete host, never a wildcard — see the module note.
|
|
105
|
+
const captureDecl = { host, path: '/*', headerName: 'authorization' };
|
|
106
|
+
// Read per capture, not at import: see `capture-window.ts`.
|
|
107
|
+
const windowMs = captureWindowMs(env);
|
|
108
|
+
const transport = createFetchproxyTransport({
|
|
109
|
+
// `createBootstrapOpts` derives the capability set from the declarations:
|
|
110
|
+
// `capture_request_header` beside mcp-utils' always-on `fetch` base verb.
|
|
111
|
+
// Same verb set as the chatsvc capture, so an existing pairing that already
|
|
112
|
+
// trusts `sharepoint.com` needs no re-approval.
|
|
113
|
+
...createBootstrapOpts({
|
|
114
|
+
domains: [...SHAREPOINT_TRUST_DOMAINS],
|
|
115
|
+
bootstrap: { captureHeaders: [{ ...captureDecl }] },
|
|
116
|
+
}),
|
|
117
|
+
port: getWsPort(),
|
|
118
|
+
// Both: the explicit deadline for every bridge version, and the declared
|
|
119
|
+
// window so mcp-utils' own derivation agrees with it.
|
|
120
|
+
fetchTimeoutMs: bridgeDeadlineMs(windowMs),
|
|
121
|
+
captureWindowMs: windowMs,
|
|
122
|
+
serverName: PACKAGE_NAME,
|
|
123
|
+
version: VERSION,
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
// `start()` loads the identity keypair. It does not bind the port or dial —
|
|
127
|
+
// that stays lazy until the first verb — but skipping it makes the first
|
|
128
|
+
// verb throw "ensureConnected called before listen()", which reads exactly
|
|
129
|
+
// like a pairing problem and is not one.
|
|
130
|
+
await transport.start();
|
|
131
|
+
try {
|
|
132
|
+
const raw = await transport.server.captureRequestHeader({
|
|
133
|
+
...captureDecl,
|
|
134
|
+
timeoutMs: windowMs,
|
|
135
|
+
});
|
|
136
|
+
if (typeof raw !== 'string') {
|
|
137
|
+
throw new Error(`${host}: capture returned no header`);
|
|
138
|
+
}
|
|
139
|
+
const token = stripBearer(raw);
|
|
140
|
+
if (token.length < MIN_TOKEN_LENGTH) {
|
|
141
|
+
throw new Error(`${host}: authorization header was present but too short to be a ` +
|
|
142
|
+
`token (${token.length} chars)`);
|
|
143
|
+
}
|
|
144
|
+
return token;
|
|
145
|
+
}
|
|
146
|
+
catch (e) {
|
|
147
|
+
const detail = e.message;
|
|
148
|
+
throw new Error(`could not capture a SharePoint token for ${host} (${detail}). ` +
|
|
149
|
+
`Click around Teams or open one of your own OneDrive files — that makes the ` +
|
|
150
|
+
`browser request ${host}, which is where the SharePoint token is captured ` +
|
|
151
|
+
'from — then retry.');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
try {
|
|
156
|
+
await transport.close();
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
/* the token, or the original failure, is what matters */
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|