@chrischall/microsoft-teams-mcp 0.13.1 → 0.15.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 +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +241 -33
- package/dist/attachments.js +238 -0
- package/dist/auth-fetchproxy.js +42 -7
- package/dist/bridge-scope.js +45 -8
- package/dist/browser-open.js +138 -0
- package/dist/bundle.js +28684 -30653
- package/dist/capture-feedback.js +283 -0
- package/dist/chatsvc.js +132 -7
- package/dist/compose.js +9 -1
- package/dist/file-upload.js +335 -0
- package/dist/index.js +11 -1
- package/dist/model.js +1 -0
- package/dist/presence.js +120 -0
- package/dist/profile.js +182 -0
- package/dist/recap-auth.js +6 -4
- package/dist/recap.js +3 -1
- package/dist/sender-email.js +147 -0
- package/dist/sharepoint-auth.js +196 -29
- package/dist/sharepoint.js +329 -8
- package/dist/substrate-auth.js +8 -7
- package/dist/substrate.js +98 -4
- package/dist/tools/attach.js +167 -0
- package/dist/tools/attachment.js +3 -1
- package/dist/tools/conversation.js +14 -5
- package/dist/tools/edit.js +42 -14
- package/dist/tools/errors.js +10 -11
- package/dist/tools/export.js +30 -3
- package/dist/tools/format.js +29 -6
- package/dist/tools/group-chat.js +349 -33
- package/dist/tools/healthcheck.js +23 -9
- package/dist/tools/mention-check.js +225 -0
- package/dist/tools/people.js +149 -39
- package/dist/tools/profile.js +67 -0
- package/dist/tools/send.js +134 -37
- package/dist/tools/sender-email-arg.js +37 -0
- package/dist/tools/token-status.js +97 -0
- package/dist/tools/unread.js +3 -2
- package/dist/tools/upload-slots.js +51 -0
- package/dist/version.js +1 -1
- package/mint.yaml +19 -0
- package/package.json +4 -1
- package/server.json +30 -2
- package/skills/teams-fpx/references/teams-env.sh +1 -1
package/dist/sharepoint.js
CHANGED
|
@@ -25,11 +25,14 @@
|
|
|
25
25
|
* As with `chatsvc.ts`, once a token is held every request is a plain Node
|
|
26
26
|
* `fetch` — the bridge is only ever touched to capture the token.
|
|
27
27
|
*/
|
|
28
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
28
29
|
import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
29
30
|
import { describeTransportFailure } from './network-error.js';
|
|
30
31
|
import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
31
32
|
import { createSharePointTokenCache } from './sharepoint-token-cache.js';
|
|
32
33
|
import { knownSharePointHosts } from './bridge-scope.js';
|
|
34
|
+
import { PACKAGE_NAME } from './version.js';
|
|
35
|
+
import { browserOpener } from './browser-open.js';
|
|
33
36
|
/**
|
|
34
37
|
* Capture a SharePoint token for `host` lazily.
|
|
35
38
|
*
|
|
@@ -43,8 +46,60 @@ async function captureSharePointTokenLazily(hosts) {
|
|
|
43
46
|
const mod = await import('./sharepoint-auth.js');
|
|
44
47
|
return mod.captureSharePointTokenViaFetchproxy(hosts);
|
|
45
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Download a shared file through the browser's own `chrome.downloads`, lazily
|
|
51
|
+
* (see {@link captureSharePointTokenLazily} for why the bridge peer is only ever
|
|
52
|
+
* imported on demand). Returns the saved local path + metadata.
|
|
53
|
+
*/
|
|
54
|
+
async function downloadViaBrowserLazily(objectUrl, env) {
|
|
55
|
+
const mod = await import('./sharepoint-auth.js');
|
|
56
|
+
return mod.downloadSharePointFileViaBrowser(objectUrl, env);
|
|
57
|
+
}
|
|
46
58
|
/** Per-request deadline, covering the body read. */
|
|
47
59
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
60
|
+
/** Per-request deadline for an upload request (a whole small file rides in one). */
|
|
61
|
+
const UPLOAD_TIMEOUT_MS = 120_000;
|
|
62
|
+
/** Sentinel: the browser `download` capability is declared but not yet granted in the bridge. */
|
|
63
|
+
const GRANT_NEEDED = Symbol('download-grant-needed');
|
|
64
|
+
/** Sentinel: the browser download got SharePoint's sign-in page — no browser session on that host yet. */
|
|
65
|
+
const SIGN_IN = Symbol('sign-in-page');
|
|
66
|
+
/**
|
|
67
|
+
* Whether a browser-download failure is specifically the `download` capability
|
|
68
|
+
* not being granted yet (the one-time approval), as opposed to the capability
|
|
69
|
+
* being unavailable (Safari) or the saved file being off-machine (hosted). The
|
|
70
|
+
* bridge reports it as `capability "download" not granted` / `capability_denied`.
|
|
71
|
+
*/
|
|
72
|
+
function isDownloadGrantMissing(err) {
|
|
73
|
+
const m = err instanceof Error ? err.message : '';
|
|
74
|
+
return /\bdownload\b/i.test(m) && /not granted|denied/i.test(m);
|
|
75
|
+
}
|
|
76
|
+
/** The host of a url for a message, or the url itself when it will not parse. */
|
|
77
|
+
function hostOf(url) {
|
|
78
|
+
try {
|
|
79
|
+
return new URL(url).host;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return url;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function pageInPlaceOfFile(data, mime, objectUrl) {
|
|
86
|
+
const head = data.subarray(0, 64 * 1024).toString('latin1');
|
|
87
|
+
const isHtml = /^text\/html\b/i.test(mime ?? '') || /^\s*<(!doctype\s+html|html|head|body|script)\b/i.test(head);
|
|
88
|
+
if (!isHtml)
|
|
89
|
+
return null;
|
|
90
|
+
if (/\/_forms\/default\.aspx/i.test(head))
|
|
91
|
+
return 'sign-in';
|
|
92
|
+
if (/g_requestAccessContext|\bAccessDenied\b/i.test(head))
|
|
93
|
+
return 'access-denied';
|
|
94
|
+
let wantsPage = false;
|
|
95
|
+
try {
|
|
96
|
+
wantsPage = /\.(x?html?|aspx?)$/i.test(new URL(objectUrl).pathname);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// An unparseable url was vetted by the browser path already; treat as a file.
|
|
100
|
+
}
|
|
101
|
+
return wantsPage ? null : 'other-page';
|
|
102
|
+
}
|
|
48
103
|
/** Run one fetch, turning "never got a response" into an error naming the host and cause. */
|
|
49
104
|
async function reachable(url, run) {
|
|
50
105
|
try {
|
|
@@ -58,6 +113,18 @@ export class SharePointClient {
|
|
|
58
113
|
#env;
|
|
59
114
|
#capture;
|
|
60
115
|
#knownHosts;
|
|
116
|
+
#browserDownload;
|
|
117
|
+
#openInBrowser;
|
|
118
|
+
#signInPollMs;
|
|
119
|
+
#signInTimeoutMs;
|
|
120
|
+
#sleep;
|
|
121
|
+
/**
|
|
122
|
+
* Per SharePoint host, the one sign-in tab this process opened for it: it
|
|
123
|
+
* settles `true` once the browser has a session there, `false` if it never
|
|
124
|
+
* did. Kept for the life of the process, so a host gets at most one tab — a
|
|
125
|
+
* second would not bring a session the first did not.
|
|
126
|
+
*/
|
|
127
|
+
#signIns = new Map();
|
|
61
128
|
#fetchImpl;
|
|
62
129
|
#cache;
|
|
63
130
|
/**
|
|
@@ -73,6 +140,11 @@ export class SharePointClient {
|
|
|
73
140
|
this.#env = opts.env ?? process.env;
|
|
74
141
|
this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
|
|
75
142
|
this.#knownHosts = opts.knownHosts ?? (() => knownSharePointHosts(this.#env));
|
|
143
|
+
this.#browserDownload = opts.browserDownload ?? ((objectUrl) => downloadViaBrowserLazily(objectUrl, this.#env));
|
|
144
|
+
this.#openInBrowser = opts.openInBrowser !== undefined ? opts.openInBrowser : browserOpener({ env: this.#env });
|
|
145
|
+
this.#signInPollMs = opts.signInPollMs ?? 2_000;
|
|
146
|
+
this.#signInTimeoutMs = opts.signInTimeoutMs ?? 30_000;
|
|
147
|
+
this.#sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
76
148
|
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
77
149
|
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
78
150
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
@@ -97,13 +169,207 @@ export class SharePointClient {
|
|
|
97
169
|
* Download the contents of a shared file by its `objectUrl` (the `url` a file
|
|
98
170
|
* attachment carries). Returns the bytes, the mime type and the byte count.
|
|
99
171
|
*
|
|
172
|
+
* Two paths, browser-first:
|
|
173
|
+
* 1. {@link #downloadViaBrowser} — `chrome.downloads` with the browser's own
|
|
174
|
+
* cookies. No token capture, so it works even when an idle Teams tab's
|
|
175
|
+
* cached token would starve the bearer capture, and on any tenant host
|
|
176
|
+
* without a per-host grant. Local installs only (it reads the saved file
|
|
177
|
+
* off the same disk).
|
|
178
|
+
* 2. {@link #downloadViaBearer} — the SharePoint v2.1 shares API with a
|
|
179
|
+
* captured bearer token. The fallback: hosted installs, Safari (no
|
|
180
|
+
* `chrome.downloads`), or a denied/failed browser download.
|
|
181
|
+
*
|
|
100
182
|
* The URL comes out of message content — i.e. it is attacker-influenced — so
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* bearer to whoever wrote the message.
|
|
183
|
+
* each path vets it (https only, a concrete `*.sharepoint.com` tenant host)
|
|
184
|
+
* BEFORE it is used. Anything else would hand the browser's cookies or the
|
|
185
|
+
* SharePoint bearer to whoever wrote the message.
|
|
104
186
|
*/
|
|
105
187
|
async downloadFile(objectUrl, maxBytes) {
|
|
106
188
|
this.#requireConfigured();
|
|
189
|
+
// An oversize file thrown here propagates (the attachment tool degrades to
|
|
190
|
+
// metadata + link) rather than falling through to the bearer path, which
|
|
191
|
+
// would otherwise capture a token only to re-derive the same limit.
|
|
192
|
+
const viaBrowser = await this.#downloadViaBrowser(objectUrl, maxBytes);
|
|
193
|
+
if (viaBrowser !== null && viaBrowser !== GRANT_NEEDED)
|
|
194
|
+
return viaBrowser;
|
|
195
|
+
// The browser path was unavailable. If it was specifically a MISSING grant
|
|
196
|
+
// (a local install where the user has not yet approved the `download`
|
|
197
|
+
// capability), the bearer path will probably hit its flaky capture — so if
|
|
198
|
+
// it fails too, tell the user the one thing that fixes everything: approve
|
|
199
|
+
// the grant. Otherwise (hosted, Safari) the bearer path is simply the way.
|
|
200
|
+
try {
|
|
201
|
+
return await this.#downloadViaBearer(objectUrl, maxBytes);
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
throw viaBrowser === GRANT_NEEDED ? this.#withGrantHint(err) : err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The browser-download path. Returns the bytes, {@link GRANT_NEEDED} when the
|
|
209
|
+
* `download` capability has not been approved in the bridge yet, or `null`
|
|
210
|
+
* when it is unavailable for any other reason (hosted install, Safari, a bad
|
|
211
|
+
* URL) — either sentinel sends the caller to the bearer path. Throws only for
|
|
212
|
+
* an oversize file: a terminal, actionable outcome.
|
|
213
|
+
*/
|
|
214
|
+
async #downloadViaBrowser(objectUrl, maxBytes) {
|
|
215
|
+
const first = await this.#browserAttempt(objectUrl, maxBytes);
|
|
216
|
+
return first === SIGN_IN ? this.#afterSignInPage(objectUrl, maxBytes) : first;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The browser download got SharePoint's sign-in page: the browser has no
|
|
220
|
+
* session on that host yet. Open the file's link in a browser tab — loading a
|
|
221
|
+
* page there runs the (normally silent) sign-on and sets the host's cookies —
|
|
222
|
+
* then retry the download until it gets past the sign-in page or the wait
|
|
223
|
+
* runs out. The tab is left open. Returns the file, or `null` to send the
|
|
224
|
+
* caller to the bearer path; an access-denied or oversize outcome on a retry
|
|
225
|
+
* throws, as on the first try.
|
|
226
|
+
*
|
|
227
|
+
* At most ONE tab per host per process (see {@link #signIns}): concurrent
|
|
228
|
+
* downloads on the host wait for that tab and then try once more, and later
|
|
229
|
+
* ones never open another.
|
|
230
|
+
*/
|
|
231
|
+
async #afterSignInPage(objectUrl, maxBytes) {
|
|
232
|
+
const host = hostOf(objectUrl);
|
|
233
|
+
const pending = this.#signIns.get(host);
|
|
234
|
+
if (pending !== undefined) {
|
|
235
|
+
if (!(await pending))
|
|
236
|
+
return null;
|
|
237
|
+
const again = await this.#browserAttempt(objectUrl, maxBytes);
|
|
238
|
+
return again === SIGN_IN || again === GRANT_NEEDED ? null : again;
|
|
239
|
+
}
|
|
240
|
+
if (this.#openInBrowser === null)
|
|
241
|
+
return null;
|
|
242
|
+
let settle = () => { };
|
|
243
|
+
this.#signIns.set(host, new Promise((resolve) => (settle = resolve)));
|
|
244
|
+
let signedIn = false;
|
|
245
|
+
try {
|
|
246
|
+
if (!(await this.#openInBrowser(objectUrl)))
|
|
247
|
+
return null;
|
|
248
|
+
const tries = Math.max(1, Math.ceil(this.#signInTimeoutMs / this.#signInPollMs));
|
|
249
|
+
for (let i = 0; i < tries; i++) {
|
|
250
|
+
await this.#sleep(this.#signInPollMs);
|
|
251
|
+
let r;
|
|
252
|
+
try {
|
|
253
|
+
r = await this.#browserAttempt(objectUrl, maxBytes);
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
// Access denied or oversize: either way the browser got past sign-in.
|
|
257
|
+
signedIn = true;
|
|
258
|
+
throw err;
|
|
259
|
+
}
|
|
260
|
+
if (r === SIGN_IN)
|
|
261
|
+
continue;
|
|
262
|
+
signedIn = r !== null && r !== GRANT_NEEDED;
|
|
263
|
+
return r === GRANT_NEEDED ? null : r;
|
|
264
|
+
}
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
settle(signedIn);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* One browser-download attempt. Returns the bytes, {@link SIGN_IN} when
|
|
273
|
+
* SharePoint served its sign-in page instead, {@link GRANT_NEEDED} when the
|
|
274
|
+
* `download` capability has not been approved in the bridge yet, or `null`
|
|
275
|
+
* when it is unavailable for any other reason (hosted install, Safari, a bad
|
|
276
|
+
* URL, some other page in place of the file). Throws for an oversize file or
|
|
277
|
+
* an access-denied page: terminal, actionable outcomes.
|
|
278
|
+
*/
|
|
279
|
+
async #browserAttempt(objectUrl, maxBytes) {
|
|
280
|
+
let meta;
|
|
281
|
+
try {
|
|
282
|
+
meta = await this.#browserDownload(objectUrl);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
// Unavailable, denied, or a bad URL — the bearer path vets and reports.
|
|
286
|
+
// A missing `download` grant is singled out so the caller can say so.
|
|
287
|
+
return isDownloadGrantMissing(err) ? GRANT_NEEDED : null;
|
|
288
|
+
}
|
|
289
|
+
if (meta === null)
|
|
290
|
+
return null;
|
|
291
|
+
// The browser reports the size before we read: refuse an oversize file
|
|
292
|
+
// without reading it, same as the bearer path's `size` check.
|
|
293
|
+
if (typeof meta.bytes === 'number' && meta.bytes > maxBytes) {
|
|
294
|
+
await this.#removeTemp(meta.path);
|
|
295
|
+
throw this.#tooLargeError(meta.bytes, maxBytes);
|
|
296
|
+
}
|
|
297
|
+
let data;
|
|
298
|
+
try {
|
|
299
|
+
data = await readFile(meta.path);
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
// The saved file is not on this machine (a hosted install) or vanished:
|
|
303
|
+
// fall back to the bearer path.
|
|
304
|
+
await this.#removeTemp(meta.path);
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
await this.#removeTemp(meta.path);
|
|
308
|
+
// A page saved in place of the file is not the file.
|
|
309
|
+
const page = pageInPlaceOfFile(data, meta.mime, objectUrl);
|
|
310
|
+
// Access denied: the browser asked as the user's own account and was
|
|
311
|
+
// refused. The bearer token is that same account, so trying it would only
|
|
312
|
+
// burn a capture timeout (~60s) to reach the same 403. Fail now, as a 403,
|
|
313
|
+
// which the attachment tool turns into "ask whoever shared it for access".
|
|
314
|
+
if (page === 'access-denied') {
|
|
315
|
+
throw new McpToolError(`Your account cannot open this file on ${hostOf(objectUrl)}.`, {
|
|
316
|
+
kind: 'http',
|
|
317
|
+
status: 403,
|
|
318
|
+
hint: 'Open its link to request access from whoever shared it, then retry.',
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
// A sign-in page: no browser session on that host yet — the caller opens a
|
|
322
|
+
// tab there and retries (see #afterSignInPage).
|
|
323
|
+
if (page === 'sign-in')
|
|
324
|
+
return SIGN_IN;
|
|
325
|
+
// Any other page: let the bearer path (one token serves every host) try,
|
|
326
|
+
// and degrade to metadata + link cleanly if it cannot.
|
|
327
|
+
if (page !== null)
|
|
328
|
+
return null;
|
|
329
|
+
// `bytes: 0` means the browser could not report the size, so the cap was not
|
|
330
|
+
// checked above — enforce it now on the real length.
|
|
331
|
+
if (data.length > maxBytes)
|
|
332
|
+
throw this.#tooLargeError(data.length, maxBytes);
|
|
333
|
+
const mimeType = typeof meta.mime === 'string' && meta.mime !== '' ? meta.mime.split(';')[0].trim() : 'application/octet-stream';
|
|
334
|
+
return { mimeType, data, size: data.length };
|
|
335
|
+
}
|
|
336
|
+
/** Delete a browser-downloaded temp file, best-effort (it was ours to clean up). */
|
|
337
|
+
async #removeTemp(path) {
|
|
338
|
+
await rm(path, { force: true }).catch(() => { });
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Append, to a failed bearer-path error, the one fix for a local install whose
|
|
342
|
+
* only problem is the un-approved `download` grant: approve it and the file
|
|
343
|
+
* downloads straight through the browser with no token capture at all.
|
|
344
|
+
*/
|
|
345
|
+
#withGrantHint(err) {
|
|
346
|
+
const extra = `If this is a local install, the simplest fix is to approve the ContextMint Bridge grant that adds ` +
|
|
347
|
+
`file download for ${PACKAGE_NAME} (open the extension popup) — then the file is fetched straight through ` +
|
|
348
|
+
`the browser with no token capture needed.`;
|
|
349
|
+
if (err instanceof McpToolError) {
|
|
350
|
+
return new McpToolError(err.message, {
|
|
351
|
+
...(err.kind !== undefined ? { kind: err.kind } : {}),
|
|
352
|
+
...(err.status !== undefined ? { status: err.status } : {}),
|
|
353
|
+
hint: err.hint !== undefined && err.hint !== '' ? `${err.hint} ${extra}` : extra,
|
|
354
|
+
cause: err,
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
return err;
|
|
358
|
+
}
|
|
359
|
+
/** The oversize-file error, shared by both download paths. */
|
|
360
|
+
#tooLargeError(size, maxBytes) {
|
|
361
|
+
const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
|
|
362
|
+
return new McpToolError(`The file is ${mb(size)}, larger than the ${mb(maxBytes)} download limit.`, {
|
|
363
|
+
kind: 'http',
|
|
364
|
+
hint: `This file is ${mb(size)}; open it with its link rather than downloading it here.`,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* The bearer-token path: the SharePoint v2.1 shares API with a token captured
|
|
369
|
+
* from the browser. The fallback when {@link #downloadViaBrowser} is
|
|
370
|
+
* unavailable.
|
|
371
|
+
*/
|
|
372
|
+
async #downloadViaBearer(objectUrl, maxBytes) {
|
|
107
373
|
let target;
|
|
108
374
|
try {
|
|
109
375
|
target = new URL(objectUrl);
|
|
@@ -138,11 +404,7 @@ export class SharePointClient {
|
|
|
138
404
|
// surfaces this hint) instead of fetching to the byte limit and tripping a
|
|
139
405
|
// less actionable read error.
|
|
140
406
|
if (typeof meta.size === 'number' && meta.size > maxBytes) {
|
|
141
|
-
|
|
142
|
-
throw new McpToolError(`The file is ${mb(meta.size)}, larger than the ${mb(maxBytes)} download limit.`, {
|
|
143
|
-
kind: 'http',
|
|
144
|
-
hint: `This file is ${mb(meta.size)}; open it with its link rather than downloading it here.`,
|
|
145
|
-
});
|
|
407
|
+
throw this.#tooLargeError(meta.size, maxBytes);
|
|
146
408
|
}
|
|
147
409
|
const downloadUrl = meta['@content.downloadUrl'];
|
|
148
410
|
if (typeof downloadUrl !== 'string' || downloadUrl === '') {
|
|
@@ -156,6 +418,65 @@ export class SharePointClient {
|
|
|
156
418
|
// in testing; the documented driveId/siteId/listItemUniqueId addressing stays
|
|
157
419
|
// out until a real 404 warrants it (plan Task 3, optional).
|
|
158
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* One authed SharePoint request, for the attachment upload (`file-upload.ts`):
|
|
423
|
+
* the URL must be https on a concrete `*.sharepoint.com` host (the bearer goes
|
|
424
|
+
* nowhere else), a redirect is an error rather than a hop that carries the
|
|
425
|
+
* bearer, and a 401 re-captures once and replays once (`withAuth`). Returns
|
|
426
|
+
* the status and the body text; the caller maps the status.
|
|
427
|
+
*/
|
|
428
|
+
async spRequest(url, init) {
|
|
429
|
+
this.#requireConfigured();
|
|
430
|
+
let target;
|
|
431
|
+
try {
|
|
432
|
+
target = new URL(url);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
throw new McpToolError('Refusing a SharePoint request whose address is not a URL.', { kind: 'unknown' });
|
|
436
|
+
}
|
|
437
|
+
const { isSharePointHost, captureHostFor } = await import('./sharepoint-auth.js');
|
|
438
|
+
if (target.protocol !== 'https:' || !isSharePointHost(target.hostname)) {
|
|
439
|
+
throw new McpToolError(`Refusing to send the SharePoint token to ${target.protocol}//${target.hostname}.`, {
|
|
440
|
+
kind: 'unknown',
|
|
441
|
+
hint: 'Only https *.sharepoint.com tenant hosts are called.',
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
this.#fileCaptureHost = captureHostFor(target.hostname);
|
|
445
|
+
let body = '';
|
|
446
|
+
const res = await this.#tokens().withAuth(async (token) => {
|
|
447
|
+
const r = await reachable(url, () => fetchBounded(url, {
|
|
448
|
+
method: init.method,
|
|
449
|
+
headers: { accept: 'application/json', ...init.headers, authorization: `Bearer ${token}` },
|
|
450
|
+
...(init.body !== undefined ? { body: init.body } : {}),
|
|
451
|
+
redirect: 'error',
|
|
452
|
+
}, { read: 'text', service: 'SharePoint', timeoutMs: UPLOAD_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
|
|
453
|
+
body = r.body;
|
|
454
|
+
return r.res;
|
|
455
|
+
});
|
|
456
|
+
return { status: res.status, body };
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* The delegated scopes (`scp`) of the SharePoint token, for an error that
|
|
460
|
+
* names what a refused write needed; `undefined` when the token is not a
|
|
461
|
+
* JWT carrying them. Captures a token if none is held.
|
|
462
|
+
*/
|
|
463
|
+
async grantedScopes() {
|
|
464
|
+
this.#requireConfigured();
|
|
465
|
+
if (this.#fileCaptureHost === '') {
|
|
466
|
+
const { captureHostFor } = await import('./sharepoint-auth.js');
|
|
467
|
+
const known = this.#knownHosts();
|
|
468
|
+
if (known.length > 0)
|
|
469
|
+
this.#fileCaptureHost = captureHostFor(known[0]);
|
|
470
|
+
}
|
|
471
|
+
const token = await this.#tokens().getAccessToken();
|
|
472
|
+
try {
|
|
473
|
+
const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
474
|
+
return typeof claims.scp === 'string' && claims.scp !== '' ? claims.scp : undefined;
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return undefined;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
159
480
|
#requireConfigured() {
|
|
160
481
|
if (this.#configError)
|
|
161
482
|
throw this.#configError;
|
package/dist/substrate-auth.js
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
*/
|
|
31
31
|
import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
|
|
32
32
|
import { captureWindowMs } from './capture-window.js';
|
|
33
|
+
import { whileWaitingGuidance } from './capture-feedback.js';
|
|
33
34
|
import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
|
|
34
35
|
import { BRIDGE_TRUST_DOMAINS, SUBSTRATE_CAPTURE_DECL } from './bridge-scope.js';
|
|
35
36
|
import { PACKAGE_NAME, VERSION } from './version.js';
|
|
@@ -45,22 +46,22 @@ export const SUBSTRATE_TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
|
|
|
45
46
|
* Capture a Substrate search token from the user's signed-in Teams tab.
|
|
46
47
|
* Returns the bare token (no `Bearer ` prefix).
|
|
47
48
|
*/
|
|
48
|
-
export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
|
|
49
|
+
export async function captureSubstrateTokenViaFetchproxy(env = process.env, windowMs = captureWindowMs(env)) {
|
|
49
50
|
return captureBearerHeader({
|
|
50
51
|
// Same verb set and, through `bridgeScopedTransport`, the same declared
|
|
51
52
|
// scope as the other two captures; only the header read differs.
|
|
52
53
|
captures: [{ ...SUBSTRATE_CAPTURE_DECL }],
|
|
53
54
|
domains: SUBSTRATE_TRUST_DOMAINS,
|
|
54
|
-
// Read per capture, not at import: see `capture-window.ts
|
|
55
|
-
windowMs
|
|
55
|
+
// Read per capture, not at import: see `capture-window.ts`; a deliberate prime passes a longer one.
|
|
56
|
+
windowMs,
|
|
56
57
|
port: getWsPort(),
|
|
57
58
|
serverName: PACKAGE_NAME,
|
|
58
59
|
version: VERSION,
|
|
59
60
|
what: 'a Substrate search token',
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
'
|
|
63
|
-
'
|
|
61
|
+
// The search has to happen WHILE the capture waits: see `capture-feedback.ts`.
|
|
62
|
+
guidance: whileWaitingGuidance('substrate', windowMs) +
|
|
63
|
+
' A "not in declared set" error means the ContextMint Bridge pairing does not trust ' +
|
|
64
|
+
'substrate.office.com yet: approve microsoft-teams-mcp in the bridge popup once.',
|
|
64
65
|
createTransport: bridgeScopedTransport(env),
|
|
65
66
|
});
|
|
66
67
|
}
|
package/dist/substrate.js
CHANGED
|
@@ -66,11 +66,21 @@
|
|
|
66
66
|
* `PublicDistributionList` — only the first can be a chat member.
|
|
67
67
|
* - The v2 query endpoint with `EntityType: "People"` is a 400: not used.
|
|
68
68
|
*
|
|
69
|
+
* The same suggestions are `teams_get_profile`'s profile cards
|
|
70
|
+
* (`profile.ts`) and `sender_email`'s addresses (`sender-email.ts`). Besides
|
|
71
|
+
* the fields above, the live sample carried `OfficeLocation` and `ImAddress`
|
|
72
|
+
* (`sip:<address>`, the card's chat address); `CompanyName`, `City` (or a
|
|
73
|
+
* `PostalAddresses[].City`) and `Manager` are read when present but were NOT
|
|
74
|
+
* seen live — the Teams card takes those from the Loki/Delve profile service,
|
|
75
|
+
* which this server does not call (another host, another token).
|
|
76
|
+
*
|
|
69
77
|
* As with the other clients, the bridge is touched only to capture the token
|
|
70
78
|
* (`substrate-auth.ts`); every request is a plain Node `fetch`.
|
|
71
79
|
*/
|
|
72
80
|
import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
73
81
|
import { describeTransportFailure } from './network-error.js';
|
|
82
|
+
import { captureWithFeedback, tokenStatusOf, whileWaitingGuidance } from './capture-feedback.js';
|
|
83
|
+
import { captureWindowMs } from './capture-window.js';
|
|
74
84
|
import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
75
85
|
import { createSubstrateTokenCache } from './substrate-token-cache.js';
|
|
76
86
|
export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
|
|
@@ -91,9 +101,9 @@ const REQUEST_TIMEOUT_MS = 30_000;
|
|
|
91
101
|
/** A search response is a page of summaries; anything near this is not one. */
|
|
92
102
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
93
103
|
/** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
|
|
94
|
-
async function captureSubstrateTokenLazily() {
|
|
104
|
+
async function captureSubstrateTokenLazily(windowMs) {
|
|
95
105
|
const mod = await import('./substrate-auth.js');
|
|
96
|
-
return mod.captureSubstrateTokenViaFetchproxy();
|
|
106
|
+
return mod.captureSubstrateTokenViaFetchproxy(undefined, windowMs);
|
|
97
107
|
}
|
|
98
108
|
/** `sent>=` takes an unquoted ISO date-time (a quoted one was mis-read live); whole seconds, rounded down. */
|
|
99
109
|
function sentBound(ms) {
|
|
@@ -256,6 +266,11 @@ function mapSuggestion(raw) {
|
|
|
256
266
|
const name = str(r.DisplayName)?.trim() ?? email ?? upn ?? mri;
|
|
257
267
|
const jobTitle = str(r.JobTitle);
|
|
258
268
|
const department = str(r.Department);
|
|
269
|
+
const company = str(r.CompanyName);
|
|
270
|
+
const officeLocation = str(r.OfficeLocation);
|
|
271
|
+
const city = str(r.City) ?? postalCity(r.PostalAddresses);
|
|
272
|
+
const chatAddress = str(r.ImAddress)?.trim().replace(/^sip:/i, '');
|
|
273
|
+
const manager = managerOf(r.Manager);
|
|
259
274
|
return {
|
|
260
275
|
mri,
|
|
261
276
|
name,
|
|
@@ -263,8 +278,35 @@ function mapSuggestion(raw) {
|
|
|
263
278
|
...(upn !== undefined ? { upn } : {}),
|
|
264
279
|
...(jobTitle !== undefined ? { jobTitle } : {}),
|
|
265
280
|
...(department !== undefined ? { department } : {}),
|
|
281
|
+
...(company !== undefined ? { company } : {}),
|
|
282
|
+
...(officeLocation !== undefined ? { officeLocation } : {}),
|
|
283
|
+
...(city !== undefined ? { city } : {}),
|
|
284
|
+
...(chatAddress ? { chatAddress } : {}),
|
|
285
|
+
...(manager !== undefined ? { manager } : {}),
|
|
266
286
|
};
|
|
267
287
|
}
|
|
288
|
+
/** The first city among a suggestion's postal addresses, if any. */
|
|
289
|
+
function postalCity(v) {
|
|
290
|
+
if (!Array.isArray(v))
|
|
291
|
+
return undefined;
|
|
292
|
+
return v.map((a) => str(obj(a)?.City)).find((c) => c !== undefined);
|
|
293
|
+
}
|
|
294
|
+
/** A manager given as a bare name, or as a person object (`DisplayName`/`Name`, `EmailAddresses`/`EmailAddress`). */
|
|
295
|
+
function managerOf(v) {
|
|
296
|
+
const name = str(v);
|
|
297
|
+
if (name !== undefined)
|
|
298
|
+
return { displayName: name.trim() };
|
|
299
|
+
const m = obj(v);
|
|
300
|
+
if (m === undefined)
|
|
301
|
+
return undefined;
|
|
302
|
+
const displayName = str(m.DisplayName) ?? str(m.Name);
|
|
303
|
+
const email = (Array.isArray(m.EmailAddresses) ? m.EmailAddresses.map(str).find((e) => e !== undefined) : undefined) ??
|
|
304
|
+
str(m.EmailAddress) ??
|
|
305
|
+
str(m.UserPrincipalName);
|
|
306
|
+
if (displayName === undefined && email === undefined)
|
|
307
|
+
return undefined;
|
|
308
|
+
return { ...(displayName !== undefined ? { displayName } : {}), ...(email !== undefined ? { email } : {}) };
|
|
309
|
+
}
|
|
268
310
|
/** Parse a suggestions response into the people who can be chat members, one per MRI. Never throws on shape. */
|
|
269
311
|
export function parseSuggestionsResponse(body) {
|
|
270
312
|
const groups = obj(body)?.Groups;
|
|
@@ -294,14 +336,28 @@ export class SubstrateClient {
|
|
|
294
336
|
* refused (401), and how; cleared by a successful capture.
|
|
295
337
|
*/
|
|
296
338
|
#captureFailure = null;
|
|
339
|
+
#env;
|
|
340
|
+
/** A longer capture window for a deliberate prime (`ensureToken({ windowMs })`), while it runs. */
|
|
341
|
+
#windowOverride;
|
|
297
342
|
constructor(opts = {}) {
|
|
298
343
|
const env = opts.env ?? process.env;
|
|
344
|
+
this.#env = env;
|
|
299
345
|
const capture = opts.captureToken ?? captureSubstrateTokenLazily;
|
|
300
346
|
// A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
|
|
301
347
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
348
|
+
// Progress while waiting, and a failure that names its step and how long it
|
|
349
|
+
// waited (`capture-feedback.ts`). No nudge: nothing but a search the person
|
|
350
|
+
// runs makes the page call the search service, and opening a tab does not.
|
|
302
351
|
const recapture = async () => {
|
|
303
352
|
try {
|
|
304
|
-
const
|
|
353
|
+
const windowMs = this.#windowOverride ?? captureWindowMs(env);
|
|
354
|
+
const previous = this.#storedExpiry() ?? this.#memoryExpiry();
|
|
355
|
+
const token = await captureWithFeedback({
|
|
356
|
+
token: 'substrate',
|
|
357
|
+
windowMs,
|
|
358
|
+
capture: () => capture(windowMs),
|
|
359
|
+
...(previous !== null ? { previousExpiresAt: previous } : {}),
|
|
360
|
+
});
|
|
305
361
|
this.#captureFailure = null;
|
|
306
362
|
return token;
|
|
307
363
|
}
|
|
@@ -326,6 +382,44 @@ export class SubstrateClient {
|
|
|
326
382
|
isConfigured() {
|
|
327
383
|
return this.#configError === null;
|
|
328
384
|
}
|
|
385
|
+
/**
|
|
386
|
+
* Hold a token — this process's, the disk cache's, or a fresh capture with
|
|
387
|
+
* `windowMs` (for this call only). Skips the failed-capture cooldown: it is
|
|
388
|
+
* the deliberate "prime the token" path.
|
|
389
|
+
*/
|
|
390
|
+
async ensureToken(opts = {}) {
|
|
391
|
+
if (this.#configError)
|
|
392
|
+
throw this.#configError;
|
|
393
|
+
this.#windowOverride = opts.windowMs;
|
|
394
|
+
try {
|
|
395
|
+
await this.#manager.getAccessToken();
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
this.#windowOverride = undefined;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** Whether a token is held and until when, WITHOUT capturing. Never the token itself. */
|
|
402
|
+
tokenStatus() {
|
|
403
|
+
return tokenStatusOf('substrate', {
|
|
404
|
+
source: 'browser capture',
|
|
405
|
+
memoryExpiresAt: this.#memoryExpiry(),
|
|
406
|
+
storedExpiresAt: this.#storedExpiry(),
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
#memoryExpiry() {
|
|
410
|
+
const at = this.#manager.getExpiresAt();
|
|
411
|
+
return Number.isFinite(at) && at > 0 ? at : null;
|
|
412
|
+
}
|
|
413
|
+
/** The disk cache's expiry, or `null`. Never throws. */
|
|
414
|
+
#storedExpiry() {
|
|
415
|
+
try {
|
|
416
|
+
const at = createSubstrateTokenCache(this.#env)?.load()?.expiresAt;
|
|
417
|
+
return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : null;
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
329
423
|
async searchMessages(req, opts = {}) {
|
|
330
424
|
return parseQueryResponse(await this.#post(SEARCH, buildQueryBody(req), opts.force === true));
|
|
331
425
|
}
|
|
@@ -408,7 +502,7 @@ function checkStatus(status, lookup) {
|
|
|
408
502
|
throw new McpToolError('Substrate rejected the search token (401) even after a fresh capture.', {
|
|
409
503
|
status,
|
|
410
504
|
kind: 'credential_rejected',
|
|
411
|
-
hint: '
|
|
505
|
+
hint: whileWaitingGuidance('substrate', captureWindowMs()),
|
|
412
506
|
});
|
|
413
507
|
}
|
|
414
508
|
if (status === 429) {
|