@chrischall/microsoft-teams-mcp 0.3.0 → 0.5.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +577 -93
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +44324 -37483
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +580 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +35 -6
  11. package/dist/model.js +603 -0
  12. package/dist/sharepoint-auth.js +162 -0
  13. package/dist/sharepoint-token-cache.js +105 -0
  14. package/dist/sharepoint.js +289 -0
  15. package/dist/substrate-auth.js +104 -0
  16. package/dist/substrate-token-cache.js +64 -0
  17. package/dist/substrate.js +319 -0
  18. package/dist/token-cache.js +67 -0
  19. package/dist/tools/activity.js +155 -19
  20. package/dist/tools/attachment.js +174 -0
  21. package/dist/tools/changes.js +241 -0
  22. package/dist/tools/channels.js +62 -44
  23. package/dist/tools/chat-search.js +65 -0
  24. package/dist/tools/chat.js +121 -41
  25. package/dist/tools/confirm.js +188 -0
  26. package/dist/tools/conversation.js +394 -30
  27. package/dist/tools/cursor.js +43 -0
  28. package/dist/tools/errors.js +18 -17
  29. package/dist/tools/format.js +135 -0
  30. package/dist/tools/healthcheck.js +91 -27
  31. package/dist/tools/limit.js +43 -12
  32. package/dist/tools/listing.js +180 -0
  33. package/dist/tools/markread.js +246 -0
  34. package/dist/tools/react.js +217 -0
  35. package/dist/tools/roots.js +73 -0
  36. package/dist/tools/search.js +426 -0
  37. package/dist/tools/send.js +309 -0
  38. package/dist/tools/timezone.js +38 -0
  39. package/dist/tools/titles.js +180 -0
  40. package/dist/tools/unread.js +263 -0
  41. package/dist/tools/untrusted.js +16 -1
  42. package/dist/version.js +1 -1
  43. package/mint.yaml +75 -20
  44. package/package.json +1 -2
  45. package/server.json +87 -3
  46. package/skills/teams-fpx/SKILL.md +111 -92
  47. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  48. package/skills/teams-fpx/references/teams-env.sh +146 -0
  49. package/dist/client.js +0 -290
  50. package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
@@ -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
+ }
@@ -0,0 +1,105 @@
1
+ import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
+ import { parseBoolEnv } from '@chrischall/mcp-utils';
3
+ import { reportCacheWriteFailure } from './token-cache.js';
4
+ /**
5
+ * Where the captured SharePoint access tokens are cached between runs.
6
+ *
7
+ * A SEPARATE file from the chat-service `token.json`: a SharePoint token is a
8
+ * different audience with a very different lifetime (~53 min vs chatsvc's ~23h),
9
+ * and there is one per SharePoint host rather than one overall — so this file
10
+ * holds a `Record<host, BearerTokens>`, not a single token. Deliberately its own
11
+ * directory for the same reason `tokenCachePath` is.
12
+ */
13
+ export function sharePointTokenCachePath(env = process.env) {
14
+ return resolveStateFile({
15
+ env,
16
+ envVar: 'TEAMS_SHAREPOINT_TOKEN_FILE',
17
+ subdir: '.microsoft-teams-mcp',
18
+ fileName: 'sharepoint-tokens.json',
19
+ });
20
+ }
21
+ /** Same `BearerTokens` guard as the chatsvc cache; copied, as it is module-private there. */
22
+ function isToken(raw) {
23
+ if (raw === null || typeof raw !== 'object')
24
+ return false;
25
+ const t = raw;
26
+ return (typeof t.accessToken === 'string' &&
27
+ t.accessToken !== '' &&
28
+ typeof t.expiresAt === 'number' &&
29
+ (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
30
+ }
31
+ /**
32
+ * Narrow the stored blob to a map of valid tokens.
33
+ *
34
+ * A non-object (or array) blob is `null` — the whole file is unusable. Otherwise
35
+ * each host's slice is validated independently and a MALFORMED one is dropped
36
+ * rather than discarding the file: a single corrupt entry must not cost every
37
+ * other host its cached token.
38
+ */
39
+ function validateMap(raw) {
40
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
41
+ return null;
42
+ const out = {};
43
+ for (const [host, value] of Object.entries(raw)) {
44
+ if (isToken(value))
45
+ out[host] = value;
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * The SharePoint token cache, or `null` when it is off or there is nothing to
51
+ * cache.
52
+ *
53
+ * Gated by the same `TEAMS_TOKEN_CACHE` (default on) as the chatsvc cache, and
54
+ * `null` under `TEAMS_DISABLE_FETCHPROXY`: a SharePoint token is only ever
55
+ * captured from the browser bridge — unlike chatsvc there is no direct-token
56
+ * env var — so with the bridge off there is nothing to cache.
57
+ */
58
+ export function createSharePointTokenCache(env = process.env) {
59
+ if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
60
+ return null;
61
+ if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
62
+ return null;
63
+ // One file-backed persistence for the whole map; the per-host views below read
64
+ // and write it. No `boundTo`: there is no single credential the whole map is
65
+ // minted from — each host's token stands or falls on its own shape.
66
+ const file = createFileStatePersistence({
67
+ filePath: sharePointTokenCachePath(env),
68
+ validate: validateMap,
69
+ });
70
+ return {
71
+ forHost(host) {
72
+ return {
73
+ load() {
74
+ return file.load()?.[host] ?? null;
75
+ },
76
+ save(tokens) {
77
+ // Read-modify-write the shared map so a sibling host's token survives.
78
+ // A failed write is reported, never thrown: a SharePoint token is
79
+ // cheap to re-capture, and a read-only data dir must not take the
80
+ // tool down — it just loses the between-run cache.
81
+ try {
82
+ const map = file.load() ?? {};
83
+ map[host] = tokens;
84
+ file.save(map);
85
+ }
86
+ catch (err) {
87
+ reportCacheWriteFailure(err);
88
+ }
89
+ },
90
+ clear() {
91
+ try {
92
+ const map = file.load();
93
+ if (map && host in map) {
94
+ delete map[host];
95
+ file.save(map);
96
+ }
97
+ }
98
+ catch (err) {
99
+ reportCacheWriteFailure(err);
100
+ }
101
+ },
102
+ };
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The SharePoint download client — fetches the CONTENTS of a shared file that
3
+ * lives in a Teams chat.
4
+ *
5
+ * A shared file is not in the Teams AMS object store inline images come from; it
6
+ * is in SharePoint, and reading it needs a SharePoint token, NOT the chat-service
7
+ * token `chatsvc.ts` holds (chatsvc's token returns 401 on SharePoint, and Graph
8
+ * `/shares` returns 403). Verified live 2026-10-11, the one route that works:
9
+ *
10
+ * GET https://{host}/_api/v2.1/shares/u!{base64url(objectUrl)}/driveItem
11
+ * ?$select=id,size,@content.downloadUrl [Authorization: Bearer <SP>]
12
+ * GET {@content.downloadUrl} [no auth — pre-signed]
13
+ * → the file's bytes
14
+ *
15
+ * The SP token is captured per host from the user's browser (see
16
+ * `sharepoint-auth.ts`), is short-lived (~53 min) and host-family-scoped, so this
17
+ * client holds one `TokenManager` per host — each with the same capture-on-401
18
+ * recovery `ChatServiceClient` has. A 403 is expected (an account that cannot
19
+ * open the file, or a host the captured token does not cover) and degrades
20
+ * gracefully; it never crashes the tool.
21
+ *
22
+ * As with `chatsvc.ts`, once a token is held every request is a plain Node
23
+ * `fetch` — the bridge is only ever touched to capture the token.
24
+ */
25
+ import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
26
+ import { TokenManager } from '@chrischall/mcp-utils/session';
27
+ import { createSharePointTokenCache } from './sharepoint-token-cache.js';
28
+ /**
29
+ * Capture a SharePoint token for `host` lazily.
30
+ *
31
+ * `sharepoint-auth.ts` pulls in `@chrischall/mcp-utils/fetchproxy`, whose
32
+ * optional `@fetchproxy/server` peer the `.mcpb` bundle ships no `node_modules`
33
+ * for — so a top-level import would throw `ERR_MODULE_NOT_FOUND` before the
34
+ * server could answer `initialize`. Deferring it (exactly as `chatsvc.ts` does
35
+ * for its own capture) keeps boot free of the bridge.
36
+ */
37
+ async function captureSharePointTokenLazily(host) {
38
+ const mod = await import('./sharepoint-auth.js');
39
+ return mod.captureSharePointTokenViaFetchproxy(host);
40
+ }
41
+ /**
42
+ * Fallback lifetime for a token whose `exp` we cannot read. Real SP tokens are
43
+ * JWTs carrying `exp` (~53 min out), so this is only reached for a malformed
44
+ * capture; deliberately short — being wrong here costs one extra 401-and-replay.
45
+ */
46
+ const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
47
+ /**
48
+ * Sentinel standing in for a refresh token this flow does not have. The token
49
+ * comes from the browser; "refreshing" means capturing a new one. `TokenManager`
50
+ * only calls `refresh` when a refresh token is present, hence the sentinel.
51
+ * (Copied from `chatsvc.ts`, where it is module-private.)
52
+ */
53
+ const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
54
+ /** Per-request deadline, covering the body read. */
55
+ const REQUEST_TIMEOUT_MS = 60_000;
56
+ /** Copied faithfully from `chatsvc.ts`: a captured token as `TokenManager` input. */
57
+ function toBearerTokens(accessToken) {
58
+ let expiresAt;
59
+ try {
60
+ // decodeJwtExp returns seconds; a non-JWT throws.
61
+ expiresAt = decodeJwtExp(accessToken) * 1000;
62
+ }
63
+ catch {
64
+ expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
65
+ }
66
+ return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
67
+ }
68
+ export class SharePointClient {
69
+ #env;
70
+ #capture;
71
+ #fetchImpl;
72
+ #cache;
73
+ /**
74
+ * Deferred configuration error. The constructor never throws, so the server
75
+ * still boots (and answers `tools/list`) with no credential present.
76
+ */
77
+ #configError = null;
78
+ /** One `TokenManager` per SharePoint host — SP tokens are host-scoped. */
79
+ #managers = new Map();
80
+ constructor(opts = {}) {
81
+ this.#env = opts.env ?? process.env;
82
+ this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
83
+ // A receiver-safe wrapper, never the bare global: older undici throws
84
+ // `Illegal invocation` when `fetch` is called with a non-global receiver.
85
+ this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
86
+ this.#cache = createSharePointTokenCache(this.#env);
87
+ // Unlike chatsvc there is NO direct-token env var: a SharePoint token is
88
+ // only ever captured from the browser, so with the bridge off there is no
89
+ // way to get one. Defer that as a clean no_credential rather than letting a
90
+ // download attempt the bridge.
91
+ if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env: this.#env })) {
92
+ this.#configError = new McpToolError('SharePoint file download is disabled (no token source).', {
93
+ kind: 'no_credential',
94
+ hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a SharePoint token can be captured from a ' +
95
+ 'signed-in Teams browser tab when a shared file is opened.',
96
+ });
97
+ }
98
+ }
99
+ /** Whether a token could be obtained at all (the bridge is not disabled). */
100
+ isConfigured() {
101
+ return this.#configError === null;
102
+ }
103
+ /**
104
+ * Download the contents of a shared file by its `objectUrl` (the `url` a file
105
+ * attachment carries). Returns the bytes, the mime type and the byte count.
106
+ *
107
+ * The URL comes out of message content — i.e. it is attacker-influenced — so
108
+ * it is vetted BEFORE a token is resolved: https only, and a concrete
109
+ * `*.sharepoint.com` tenant host. Anything else would hand the SharePoint
110
+ * bearer to whoever wrote the message.
111
+ */
112
+ async downloadFile(objectUrl, maxBytes) {
113
+ this.#requireConfigured();
114
+ let target;
115
+ try {
116
+ target = new URL(objectUrl);
117
+ }
118
+ catch {
119
+ throw new McpToolError('Refusing to download a file whose link is not a URL.', {
120
+ hint: 'Pass a file url exactly as a message listing returned it.',
121
+ });
122
+ }
123
+ // `isSharePointHost` lives in the lazily-imported auth module (see
124
+ // `captureSharePointTokenLazily`); loaded here too so the host is vetted with
125
+ // the one authoritative check rather than a duplicate.
126
+ const { isSharePointHost } = await import('./sharepoint-auth.js');
127
+ const host = target.hostname;
128
+ if (target.protocol !== 'https:' || !isSharePointHost(host)) {
129
+ throw new McpToolError(`Refusing to download a file from ${target.protocol}//${host}.`, {
130
+ hint: 'Only https files on a *.sharepoint.com tenant host are downloaded.',
131
+ });
132
+ }
133
+ // The driveItem GET goes to the FILE's host, but the token is captured from
134
+ // (and cached under) the user's OneDrive host — the browser authenticates
135
+ // that host, and its token reads the tenant root too. See `captureHostFor`.
136
+ const { captureHostFor } = await import('./sharepoint-auth.js');
137
+ const captureHost = captureHostFor(host);
138
+ // `u!` + unpadded base64url of the full objectUrl (Node's `base64url` already
139
+ // uses `-`/`_` and drops padding), matching the live spike.
140
+ const share = `u!${Buffer.from(objectUrl, 'utf8').toString('base64url')}`;
141
+ const driveItemUrl = `https://${host}/_api/v2.1/shares/${share}/driveItem?$select=id,size,@content.downloadUrl`;
142
+ const meta = await this.#getDriveItem(captureHost, driveItemUrl);
143
+ // Refuse an oversize file BEFORE streaming it: the driveItem carries `size`,
144
+ // so a file past the cap degrades to metadata + link (the attachment tool
145
+ // surfaces this hint) instead of fetching to the byte limit and tripping a
146
+ // less actionable read error.
147
+ if (typeof meta.size === 'number' && meta.size > maxBytes) {
148
+ const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
149
+ throw new McpToolError(`The file is ${mb(meta.size)}, larger than the ${mb(maxBytes)} download limit.`, {
150
+ kind: 'http',
151
+ hint: `This file is ${mb(meta.size)}; open it with its link rather than downloading it here.`,
152
+ });
153
+ }
154
+ const downloadUrl = meta['@content.downloadUrl'];
155
+ if (typeof downloadUrl !== 'string' || downloadUrl === '') {
156
+ throw new McpToolError('SharePoint returned no download link for the file.', {
157
+ kind: 'http',
158
+ hint: 'The file may be a folder or a format with no direct content; open it with its link.',
159
+ });
160
+ }
161
+ return this.#fetchContent(downloadUrl, maxBytes);
162
+ // fallback: sharepointIds route — the proven shares route above has not 404'd
163
+ // in testing; the documented driveId/siteId/listItemUniqueId addressing stays
164
+ // out until a real 404 warrants it (plan Task 3, optional).
165
+ }
166
+ #requireConfigured() {
167
+ if (this.#configError)
168
+ throw this.#configError;
169
+ }
170
+ /** The `TokenManager` for `host`, created (and cached) on first use. */
171
+ #managerFor(host) {
172
+ const existing = this.#managers.get(host);
173
+ if (existing)
174
+ return existing;
175
+ // The per-host cache view already swallows-and-reports its own write
176
+ // failures (see `sharepoint-token-cache.ts`), so it is passed straight
177
+ // through — no inline wrapping as chatsvc needs for its raw persistence.
178
+ const persistence = this.#cache?.forHost(host);
179
+ const mgr = new TokenManager({
180
+ initial: async () => toBearerTokens(await this.#capture(host)),
181
+ // No refresh grant — re-capture instead.
182
+ refresh: async () => toBearerTokens(await this.#capture(host)),
183
+ ...(persistence ? { persistence } : {}),
184
+ });
185
+ this.#managers.set(host, mgr);
186
+ return mgr;
187
+ }
188
+ /**
189
+ * The authed driveItem GET, with chatsvc's discipline: `behavioroverride:
190
+ * redirectAs404` so a failure is a status rather than a sign-in redirect, and
191
+ * `redirect: 'error'` so a redirect never carries the bearer somewhere unvetted.
192
+ * `TokenManager.withAuth` supplies the token and, on a 401, re-captures once
193
+ * and replays once — so a 401 that reaches here is the second one.
194
+ */
195
+ async #getDriveItem(captureHost, url) {
196
+ let body = '';
197
+ const res = await this.#managerFor(captureHost).withAuth(async (token) => {
198
+ const r = await fetchBounded(url, {
199
+ method: 'GET',
200
+ headers: {
201
+ authorization: `Bearer ${token}`,
202
+ accept: 'application/json',
203
+ behavioroverride: 'redirectAs404',
204
+ },
205
+ redirect: 'error',
206
+ }, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
207
+ body = r.body;
208
+ return r.res;
209
+ });
210
+ const status = res.status;
211
+ if (status === 403) {
212
+ // mcp-utils' `kind` vocabulary has no 'forbidden'; the 403 is carried by
213
+ // `status`, which the attachment tool reads to degrade to metadata + link.
214
+ throw new McpToolError('SharePoint refused access to the file (403).', {
215
+ status,
216
+ kind: 'http',
217
+ hint: 'Your account cannot open this file, or it is on a SharePoint host your captured ' +
218
+ 'token does not cover. Open it once in Teams, then retry.',
219
+ });
220
+ }
221
+ if (status === 404) {
222
+ throw new McpToolError('SharePoint has no such file (404).', {
223
+ status,
224
+ kind: 'http',
225
+ hint: 'The file may have moved or been deleted; open it with its link to check.',
226
+ });
227
+ }
228
+ return this.#parseJson(status, body);
229
+ }
230
+ /**
231
+ * Fetch the pre-signed download link with NO Authorization header. It 302s to
232
+ * a CDN/blob host, which is safe to follow precisely because no bearer is
233
+ * attached; the read is bounded to `maxBytes`. https only.
234
+ */
235
+ async #fetchContent(downloadUrl, maxBytes) {
236
+ let target;
237
+ try {
238
+ target = new URL(downloadUrl);
239
+ }
240
+ catch {
241
+ throw new McpToolError('SharePoint returned a download link that is not a URL.', { kind: 'http' });
242
+ }
243
+ if (target.protocol !== 'https:') {
244
+ throw new McpToolError(`Refusing to fetch a download link over ${target.protocol}.`, {
245
+ kind: 'http',
246
+ hint: 'SharePoint download links are expected to be https.',
247
+ });
248
+ }
249
+ const r = await fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
250
+ this.#checkStatus(r.status);
251
+ const mimeType = (r.headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
252
+ const data = Buffer.from(r.body);
253
+ return { mimeType, data, size: data.length };
254
+ }
255
+ #parseJson(status, body) {
256
+ this.#checkStatus(status);
257
+ try {
258
+ return JSON.parse(body);
259
+ }
260
+ catch {
261
+ // Never echo the body: it may be the file's metadata or an error page.
262
+ throw new McpToolError('SharePoint returned a response that is not JSON.', { status, kind: 'http' });
263
+ }
264
+ }
265
+ /** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
266
+ #checkStatus(status) {
267
+ if (status >= 200 && status < 300)
268
+ return;
269
+ if (status === 401) {
270
+ throw new McpToolError('SharePoint rejected the access token (401) even after a fresh capture.', {
271
+ status,
272
+ kind: 'credential_rejected',
273
+ hint: 'Open the shared file once in a signed-in Teams tab to mint a fresh SharePoint token, then retry.',
274
+ });
275
+ }
276
+ if (status === 429) {
277
+ throw new McpToolError('SharePoint is rate-limiting requests (429).', {
278
+ status,
279
+ kind: 'http',
280
+ hint: 'Wait a minute before retrying.',
281
+ });
282
+ }
283
+ throw new McpToolError(`SharePoint returned HTTP ${status}.`, {
284
+ status,
285
+ kind: 'http',
286
+ ...(status >= 500 ? { hint: 'A SharePoint-side failure; retry shortly.' } : {}),
287
+ });
288
+ }
289
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Bootstrap-only fetchproxy auth for Microsoft Substrate search — the backend
3
+ * the Teams web client's own search box uses (`teams_search_messages`).
4
+ *
5
+ * Substrate does not accept the chat-service token (its audience is
6
+ * `https://ic3.teams.office.com`), so search needs a THIRD token, captured the
7
+ * same way the other two are: we snapshot the `Authorization: Bearer …` header
8
+ * off a request the signed-in Teams tab makes to
9
+ * `substrate.office.com/searchservice/*` — which it does when the user runs a
10
+ * search in Teams' search box — and then talk to Substrate with a plain Node
11
+ * `fetch` (`substrate.ts`). Requests only: nothing here, or anywhere in this
12
+ * MCP, reads a token out of page storage.
13
+ *
14
+ * The capture path is restricted to `/searchservice/*` rather than `/*`: other
15
+ * Substrate APIs the page calls are minted for other scopes, and a token lifted
16
+ * off one of those could fail on the search API in ways that look like a
17
+ * Substrate outage.
18
+ *
19
+ * Verified live 2026-10-12: after a one-time pair approval in the ContextMint
20
+ * Bridge popup (the `substrate.office.com` scope), running any search in the
21
+ * Teams search box during the capture window yielded a token off
22
+ * `/searchservice/*` (an app-GUID audience, ~1.4h lifetime) that
23
+ * `substrate.ts` replayed successfully from Node. Until the pair is approved,
24
+ * the capture fails fast with "pairing required" and search falls back to the
25
+ * scan.
26
+ *
27
+ * Import this module LAZILY (`await import('./substrate-auth.js')`), as
28
+ * `sharepoint-auth.ts` is, so a server run with `TEAMS_DISABLE_FETCHPROXY`
29
+ * never has to load the bridge to boot.
30
+ */
31
+ import { createBootstrapOpts, createFetchproxyTransport } from '@chrischall/mcp-utils/fetchproxy';
32
+ import { bridgeDeadlineMs, captureWindowMs } from './capture-window.js';
33
+ import { getWsPort, stripBearer } from './auth-fetchproxy.js';
34
+ import { PACKAGE_NAME, VERSION } from './version.js';
35
+ /** The one request we capture from: a search-service call the Teams tab makes. */
36
+ export const SUBSTRATE_CAPTURE_DECL = {
37
+ host: 'substrate.office.com',
38
+ path: '/searchservice/*',
39
+ headerName: 'authorization',
40
+ };
41
+ /**
42
+ * The extension's trust boundary for search: exactly the host we capture from.
43
+ * A third, independent scope beside `teams.cloud.microsoft` and
44
+ * `sharepoint.com` — granting it takes a one-time re-pair of
45
+ * `microsoft-teams-mcp` in the ContextMint Bridge popup; until then search falls
46
+ * back to the client-side scan.
47
+ */
48
+ export const SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
49
+ /** Shortest plausible token; guards against an empty or echoed header only. */
50
+ const MIN_TOKEN_LENGTH = 100;
51
+ /**
52
+ * Capture a Substrate search token from the user's signed-in Teams tab.
53
+ * Returns the bare token (no `Bearer ` prefix).
54
+ */
55
+ export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
56
+ // Read per capture, not at import: see `capture-window.ts`.
57
+ const windowMs = captureWindowMs(env);
58
+ const transport = createFetchproxyTransport({
59
+ // Same verb set as the other two captures (`capture_request_header` beside
60
+ // the always-on `fetch`); only the trusted domain differs.
61
+ ...createBootstrapOpts({
62
+ domains: [...SUBSTRATE_TRUST_DOMAINS],
63
+ bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] },
64
+ }),
65
+ port: getWsPort(),
66
+ fetchTimeoutMs: bridgeDeadlineMs(windowMs),
67
+ captureWindowMs: windowMs,
68
+ serverName: PACKAGE_NAME,
69
+ version: VERSION,
70
+ });
71
+ try {
72
+ // Loads the identity keypair; skipping it makes the first verb throw
73
+ // "ensureConnected called before listen()" (see `auth-fetchproxy.ts`).
74
+ await transport.start();
75
+ try {
76
+ const raw = await transport.server.captureRequestHeader({ ...SUBSTRATE_CAPTURE_DECL, timeoutMs: windowMs });
77
+ if (typeof raw !== 'string') {
78
+ throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: capture returned no header`);
79
+ }
80
+ const token = stripBearer(raw);
81
+ if (token.length < MIN_TOKEN_LENGTH) {
82
+ throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: authorization header was present but too short to be a ` +
83
+ `token (${token.length} chars)`);
84
+ }
85
+ return token;
86
+ }
87
+ catch (e) {
88
+ const detail = e.message;
89
+ throw new Error(`could not capture a Substrate search token from the browser (${detail}). ` +
90
+ 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
91
+ 'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
92
+ 'is read from — then retry. A "not in declared set" error means the ContextMint Bridge ' +
93
+ 'pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.');
94
+ }
95
+ }
96
+ finally {
97
+ try {
98
+ await transport.close();
99
+ }
100
+ catch {
101
+ /* the token, or the original failure, is what matters */
102
+ }
103
+ }
104
+ }