@chrischall/microsoft-teams-mcp 0.6.0 → 0.6.2

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.
@@ -1,10 +1,11 @@
1
1
  /**
2
- * How long a token capture may wait, and the bridge deadline that has to
3
- * outlast it.
2
+ * How long a token capture may wait. (`captureBearerHeader` derives the
3
+ * bridge deadline that has to outlast it: the window + 15 s, never under the
4
+ * library's 30 s.)
4
5
  *
5
6
  * Kept free of any bridge import, so it can be read and tested without
6
7
  * loading `auth-fetchproxy.ts` (the one transport this MCP builds) and its
7
- * optional `@fetchproxy/server` peer. Both are read at CALL time, not module
8
+ * optional `@fetchproxy/server` peer. It is read at CALL time, not module
8
9
  * load, so `TEAMS_CAPTURE_TIMEOUT` set by the host's env (or a `.env` loaded
9
10
  * after import) is honoured.
10
11
  */
@@ -18,24 +19,8 @@ import { readTtlMsEnv } from '@chrischall/mcp-utils';
18
19
  * not hang a tool call for minutes.
19
20
  */
20
21
  export const DEFAULT_CAPTURE_WINDOW_MS = 30_000;
21
- /** How far the bridge deadline outlasts the capture window (one round trip, generously). */
22
- export const DEADLINE_MARGIN_MS = 15_000;
23
- /** `@fetchproxy/server`'s own default deadline; never go below it. */
24
- const MIN_DEADLINE_MS = 30_000;
25
22
  /** `TEAMS_CAPTURE_TIMEOUT` (seconds) as milliseconds. */
26
23
  export function captureWindowMs(env = process.env) {
27
24
  const ms = readTtlMsEnv('TEAMS_CAPTURE_TIMEOUT', DEFAULT_CAPTURE_WINDOW_MS, { env });
28
25
  return ms > 0 ? ms : DEFAULT_CAPTURE_WINDOW_MS;
29
26
  }
30
- /**
31
- * The transport-wide deadline (`fetchTimeoutMs`) for a capture window.
32
- *
33
- * A verb's own `timeoutMs` is cut off by `fetchTimeoutMs` on older bridges, so
34
- * a window raised past the deadline fails early at the deadline's number —
35
- * which reads as a timeout nobody configured. Deriving it means the two cannot
36
- * disagree, and the extension's own "no request arrived" answer is the one the
37
- * caller sees.
38
- */
39
- export function bridgeDeadlineMs(windowMs) {
40
- return Math.max(windowMs + DEADLINE_MARGIN_MS, MIN_DEADLINE_MS);
41
- }
package/dist/chatsvc.js CHANGED
@@ -19,8 +19,8 @@
19
19
  * live facts" section of `docs/plans/2026-10-10-chatsvc-api.md` for the
20
20
  * response shapes the types below describe.
21
21
  */
22
- import { decodeJwtClaim, decodeJwtExp, fetchBounded, errorKindOf, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
23
- import { TokenManager } from '@chrischall/mcp-utils/session';
22
+ import { decodeJwtClaim, fetchBounded, errorKindOf, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
23
+ import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
24
24
  import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
25
25
  import { SELF_CHAT } from './model.js';
26
26
  import { describeTransportFailure } from './network-error.js';
@@ -50,22 +50,6 @@ export function chatServiceBase(env = process.env) {
50
50
  const region = readEnvVar('TEAMS_CHATSVC_REGION', { env }) ?? DEFAULT_REGION;
51
51
  return `https://teams.cloud.microsoft/api/chatsvc/${encodeURIComponent(region)}/v1`;
52
52
  }
53
- /**
54
- * Fallback lifetime for a token whose `exp` we cannot read.
55
- *
56
- * Real tokens are JWTs carrying `exp` (~23.5h out), so this is only reached
57
- * for a hand-supplied opaque `TEAMS_ACCESS_TOKEN`. Deliberately short: being
58
- * wrong in this direction costs one extra 401-and-replay.
59
- */
60
- const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
61
- /**
62
- * Sentinel standing in for a refresh token this flow does not have.
63
- *
64
- * The token comes from MSAL's hidden-iframe flow; there is no refresh grant we
65
- * can drive, so "refreshing" means capturing a new one. `TokenManager` only
66
- * calls `refresh` when a refresh token is present, hence the sentinel.
67
- */
68
- const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
69
53
  /** Per-request deadline, covering the body read. */
70
54
  const REQUEST_TIMEOUT_MS = 60_000;
71
55
  /** Paging caps — a runaway `backwardLink` chain must not hold a tool call open. */
@@ -121,26 +105,6 @@ const SEND_OUTCOME_HINT = 'The message may already have been posted — check th
121
105
  const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
122
106
  const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_read_conversation) before retrying; ' +
123
107
  'moving it again to the same message is harmless.';
124
- /**
125
- * The HTTP status behind a {@link WriteOutcomeUnknownError} that Teams
126
- * answered with a 5xx, or `undefined` when it timed out or the connection
127
- * dropped instead.
128
- */
129
- export function outcomeUnknownStatus(e) {
130
- const status = e.cause?.status;
131
- return typeof status === 'number' ? status : undefined;
132
- }
133
- function toBearerTokens(accessToken) {
134
- let expiresAt;
135
- try {
136
- // decodeJwtExp returns seconds; a non-JWT throws.
137
- expiresAt = decodeJwtExp(accessToken) * 1000;
138
- }
139
- catch {
140
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
141
- }
142
- return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
143
- }
144
108
  export class ChatServiceClient {
145
109
  #baseUrl;
146
110
  /**
@@ -441,46 +405,18 @@ export class ChatServiceClient {
441
405
  throw this.#configError;
442
406
  }
443
407
  #tokenManager() {
444
- if (this.#tokens)
445
- return this.#tokens;
446
- const direct = this.#direct;
447
- const persistence = direct === undefined ? createTokenCache(this.#env) : null;
448
- const mint = async () => toBearerTokens(direct ?? (await this.#capture()));
449
- this.#tokens = new TokenManager({
450
- initial: mint,
451
- // There is no refresh grant — re-capture instead. But a token supplied as
452
- // TEAMS_ACCESS_TOKEN must NOT be "refreshed" from the browser: that would
453
- // silently swap the operator's chosen credential for whichever account a
454
- // tab is signed into.
455
- refresh: async () => {
456
- if (direct !== undefined)
457
- throw this.#directRejected();
458
- return toBearerTokens(await this.#capture());
459
- },
460
- // A failed cache write must not fail the call that triggered it.
461
- ...(persistence
462
- ? {
463
- persistence: {
464
- load: () => persistence.load(),
465
- save: (t) => {
466
- try {
467
- persistence.save(t);
468
- }
469
- catch (e) {
470
- reportCacheWriteFailure(e);
471
- }
472
- },
473
- clear: () => {
474
- try {
475
- persistence.clear();
476
- }
477
- catch {
478
- /* nothing useful to do; the next capture overwrites it */
479
- }
480
- },
481
- },
482
- }
483
- : {}),
408
+ // Captures on first use (or loads a still-valid cached capture), re-captures
409
+ // on a 401 or inside the skew window, and expires a JWT at its `exp` (an
410
+ // opaque token after 10 minutes). A token supplied as TEAMS_ACCESS_TOKEN is
411
+ // never cached and never "refreshed" from the browser: that would silently
412
+ // swap the operator's chosen credential for whichever account a tab is
413
+ // signed into. A failed cache write is reported, never fatal.
414
+ this.#tokens ??= createCapturedTokenManager({
415
+ capture: () => this.#capture(),
416
+ direct: this.#direct,
417
+ onDirectRejected: () => this.#directRejected(),
418
+ persistence: this.#direct === undefined ? createTokenCache(this.#env) : null,
419
+ onPersistError: reportCacheWriteFailure,
484
420
  });
485
421
  return this.#tokens;
486
422
  }
@@ -8,117 +8,30 @@
8
8
  * which names neither the host nor the reason (2026-10-12: two inline images
9
9
  * on `in-api`/`us-api.asm.skype.com` failed that way on a machine whose
10
10
  * chat-service calls to `teams.cloud.microsoft` were fine, while the same refs
11
- * downloaded on another machine). This turns it into an `McpToolError` naming
12
- * the HOST — never the path or query, which may carry ids — the cause's code,
13
- * and a hint keyed to that code.
11
+ * downloaded on another machine).
12
+ *
13
+ * The classifier is mcp-utils' `describeTransportFailure` (lifted from this
14
+ * file): an `McpToolError` naming the HOST — never the path or query, which
15
+ * may carry ids — the cause's code, and a hint keyed to that code. Only two
16
+ * hints are Teams-specific, below.
14
17
  */
15
- import { McpToolError } from '@chrischall/mcp-utils';
16
- /** How far down a cause chain (and into an AggregateError) to look for a code. */
17
- const MAX_CAUSE_DEPTH = 5;
18
- const DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NONAME']);
19
- const CONNECT_CODES = new Set([
20
- 'ECONNREFUSED',
21
- 'ECONNRESET',
22
- 'ETIMEDOUT',
23
- 'ENETUNREACH',
24
- 'EHOSTUNREACH',
25
- 'EPIPE',
26
- 'UND_ERR_CONNECT_TIMEOUT',
27
- 'UND_ERR_SOCKET',
28
- 'UND_ERR_HEADERS_TIMEOUT',
29
- ]);
30
- const CERT_CODES = new Set([
31
- 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
32
- 'UNABLE_TO_GET_ISSUER_CERT',
33
- 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
34
- 'SELF_SIGNED_CERT_IN_CHAIN',
35
- 'DEPTH_ZERO_SELF_SIGNED_CERT',
36
- 'CERT_HAS_EXPIRED',
37
- 'CERT_NOT_YET_VALID',
38
- 'ERR_TLS_CERT_ALTNAME_INVALID',
39
- ]);
40
- function codeOf(e) {
41
- if (e === null || typeof e !== 'object')
42
- return undefined;
43
- const code = e.code;
44
- return typeof code === 'string' && code !== '' ? code : undefined;
45
- }
46
- /** The causes to look at, nearest first: the cause chain, and an AggregateError's members. */
47
- function causes(err) {
48
- const out = [];
49
- let at = err;
50
- for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== undefined && at !== null; depth++) {
51
- out.push(at);
52
- if (at instanceof AggregateError)
53
- out.push(...at.errors);
54
- at = at.cause;
55
- }
56
- return out;
57
- }
58
- /** The first system/undici error code on `err`'s cause chain. */
59
- export function transportCauseCode(err) {
60
- for (const e of causes(err)) {
61
- const code = codeOf(e);
62
- if (code !== undefined)
63
- return code;
64
- }
65
- return undefined;
66
- }
67
- /** The innermost cause's message, which is where undici puts the real reason. */
68
- function causeMessage(err) {
69
- const chain = causes(err).slice(1);
70
- for (let i = chain.length - 1; i >= 0; i--) {
71
- const e = chain[i];
72
- if (e instanceof Error && e.message !== '')
73
- return e.message;
74
- }
75
- return undefined;
76
- }
77
- /** Whether `err` is `fetch`'s "never got a response" failure. */
78
- function isFetchFailed(err) {
79
- return err instanceof TypeError && err.message === 'fetch failed';
80
- }
81
- function hintFor(code, host) {
82
- if (code !== undefined && DNS_CODES.has(code)) {
83
- return (`This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves ` +
84
- 'teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts ' +
85
- `fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`);
86
- }
87
- if (code !== undefined && CERT_CODES.has(code)) {
88
- return (`Node did not trust the TLS certificate ${host} presented. On a corporate network this is ` +
89
- 'usually TLS inspection: export your proxy\'s root CA as PEM and start this server with ' +
90
- 'NODE_EXTRA_CA_CERTS=/path/to/ca.pem (Node does not read the system keychain). If the ' +
91
- 'certificate is expired or not yet valid, also check the machine\'s clock.');
92
- }
93
- if (code !== undefined && CONNECT_CODES.has(code)) {
94
- return (`The connection to ${host} was refused, reset or timed out before Teams answered — usually a ` +
95
- 'firewall, or a network that only lets traffic out through a proxy. Node\'s fetch ignores ' +
96
- 'proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and ' +
97
- 'NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.');
98
- }
99
- return (`No response from ${host}. Check this machine can reach it (VPN, proxy, firewall); ` +
100
- `\`curl -sI https://${host}/\` from the same machine is a quick test.`);
101
- }
18
+ import { describeTransportFailure as describe } from '@chrischall/mcp-utils';
19
+ export { transportCauseCode } from '@chrischall/mcp-utils';
20
+ const TEAMS_HINTS = {
21
+ // Name the hosts a split-tunnel VPN actually fails on for Teams.
22
+ dns: (host) => `This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves ` +
23
+ 'teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts ' +
24
+ `fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`,
25
+ // "before Teams answered", whichever Teams host (image store, gateway, SharePoint) it was.
26
+ connect: (host) => `The connection to ${host} was refused, reset or timed out before Teams answered — usually a ` +
27
+ "firewall, or a network that only lets traffic out through a proxy. Node's fetch ignores " +
28
+ 'proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and ' +
29
+ 'NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.',
30
+ };
102
31
  /**
103
32
  * An `McpToolError` describing `err` when it is `fetch`'s transport failure
104
33
  * for `url`, else `undefined` (the caller rethrows `err` as it was).
105
34
  */
106
35
  export function describeTransportFailure(err, url, service) {
107
- if (!isFetchFailed(err))
108
- return undefined;
109
- let host;
110
- try {
111
- host = new URL(url).hostname;
112
- }
113
- catch {
114
- host = '(unknown host)';
115
- }
116
- const code = transportCauseCode(err);
117
- const detail = [code, causeMessage(err)].filter((s) => s !== undefined);
118
- const why = detail.length > 0 ? ` (${[...new Set(detail)].join(': ')})` : '';
119
- return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
120
- kind: 'transport',
121
- hint: hintFor(code, host),
122
- cause: err,
123
- });
36
+ return describe(err, url, service, { hints: TEAMS_HINTS });
124
37
  }
@@ -38,9 +38,9 @@
38
38
  * code that needs a token, as `auth-fetchproxy.ts` is, so a server run with
39
39
  * `TEAMS_DISABLE_FETCHPROXY` never has to load the bridge to boot.
40
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';
41
+ import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
42
+ import { captureWindowMs } from './capture-window.js';
43
+ import { createCaptureTransport, getWsPort } from './auth-fetchproxy.js';
44
44
  import { PACKAGE_NAME, VERSION } from './version.js';
45
45
  /**
46
46
  * The extension's trust boundary for the SharePoint path: the broad family
@@ -82,11 +82,6 @@ export function captureHostFor(fileHost) {
82
82
  const m = /^([a-z0-9][a-z0-9-]*)\.sharepoint\.com$/.exec(h);
83
83
  return m ? `${m[1]}-my.sharepoint.com` : h;
84
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
85
  /**
91
86
  * Capture a SharePoint access token for `host` from the user's signed-in Teams
92
87
  * tab. Returns the bare token (no `Bearer ` prefix).
@@ -99,64 +94,24 @@ export async function captureSharePointTokenViaFetchproxy(host, env = process.en
99
94
  throw new Error(`refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a ` +
100
95
  '*.sharepoint.com host');
101
96
  }
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
- }),
97
+ return captureBearerHeader({
98
+ // The one request we capture from: any call the browser makes to this
99
+ // OneDrive host (the caller resolves it from the file's host via
100
+ // `captureHostFor`). A concrete host, never a wildcard — see the module note.
101
+ captures: [{ host, path: '/*', headerName: 'authorization' }],
102
+ // The broad family domain as the trust scope. Same verb set as the chatsvc
103
+ // capture, so an existing pairing that already trusts `sharepoint.com`
104
+ // needs no re-approval.
105
+ domains: SHAREPOINT_TRUST_DOMAINS,
106
+ // Read per capture, not at import: see `capture-window.ts`.
107
+ windowMs: captureWindowMs(env),
117
108
  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
109
  serverName: PACKAGE_NAME,
123
110
  version: VERSION,
111
+ what: `a SharePoint token for ${host}`,
112
+ guidance: `Click around Teams or open one of your own OneDrive files — that makes the ` +
113
+ `browser request ${host}, which is where the SharePoint token is captured ` +
114
+ 'from — then retry.',
115
+ createTransport: createCaptureTransport,
124
116
  });
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
117
  }
@@ -1,4 +1,4 @@
1
- import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
1
+ import { createFileStatePersistence, isBearerTokens, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
2
  import { parseBoolEnv } from '@chrischall/mcp-utils';
3
3
  import { reportCacheWriteFailure } from './token-cache.js';
4
4
  /**
@@ -18,16 +18,6 @@ export function sharePointTokenCachePath(env = process.env) {
18
18
  fileName: 'sharepoint-tokens.json',
19
19
  });
20
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
21
  /**
32
22
  * Narrow the stored blob to a map of valid tokens.
33
23
  *
@@ -41,7 +31,7 @@ function validateMap(raw) {
41
31
  return null;
42
32
  const out = {};
43
33
  for (const [host, value] of Object.entries(raw)) {
44
- if (isToken(value))
34
+ if (isBearerTokens(value))
45
35
  out[host] = value;
46
36
  }
47
37
  return out;
@@ -22,9 +22,9 @@
22
22
  * As with `chatsvc.ts`, once a token is held every request is a plain Node
23
23
  * `fetch` — the bridge is only ever touched to capture the token.
24
24
  */
25
- import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
25
+ import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
26
26
  import { describeTransportFailure } from './network-error.js';
27
- import { TokenManager } from '@chrischall/mcp-utils/session';
27
+ import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
28
28
  import { createSharePointTokenCache } from './sharepoint-token-cache.js';
29
29
  /**
30
30
  * Capture a SharePoint token for `host` lazily.
@@ -39,19 +39,6 @@ async function captureSharePointTokenLazily(host) {
39
39
  const mod = await import('./sharepoint-auth.js');
40
40
  return mod.captureSharePointTokenViaFetchproxy(host);
41
41
  }
42
- /**
43
- * Fallback lifetime for a token whose `exp` we cannot read. Real SP tokens are
44
- * JWTs carrying `exp` (~53 min out), so this is only reached for a malformed
45
- * capture; deliberately short — being wrong here costs one extra 401-and-replay.
46
- */
47
- const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
48
- /**
49
- * Sentinel standing in for a refresh token this flow does not have. The token
50
- * comes from the browser; "refreshing" means capturing a new one. `TokenManager`
51
- * only calls `refresh` when a refresh token is present, hence the sentinel.
52
- * (Copied from `chatsvc.ts`, where it is module-private.)
53
- */
54
- const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
55
42
  /** Per-request deadline, covering the body read. */
56
43
  const REQUEST_TIMEOUT_MS = 60_000;
57
44
  /** Run one fetch, turning "never got a response" into an error naming the host and cause. */
@@ -63,18 +50,6 @@ async function reachable(url, run) {
63
50
  throw describeTransportFailure(e, url, 'SharePoint') ?? e;
64
51
  }
65
52
  }
66
- /** Copied faithfully from `chatsvc.ts`: a captured token as `TokenManager` input. */
67
- function toBearerTokens(accessToken) {
68
- let expiresAt;
69
- try {
70
- // decodeJwtExp returns seconds; a non-JWT throws.
71
- expiresAt = decodeJwtExp(accessToken) * 1000;
72
- }
73
- catch {
74
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
75
- }
76
- return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
77
- }
78
53
  export class SharePointClient {
79
54
  #env;
80
55
  #capture;
@@ -185,12 +160,11 @@ export class SharePointClient {
185
160
  // The per-host cache view already swallows-and-reports its own write
186
161
  // failures (see `sharepoint-token-cache.ts`), so it is passed straight
187
162
  // through — no inline wrapping as chatsvc needs for its raw persistence.
188
- const persistence = this.#cache?.forHost(host);
189
- const mgr = new TokenManager({
190
- initial: async () => toBearerTokens(await this.#capture(host)),
191
- // No refresh grant — re-capture instead.
192
- refresh: async () => toBearerTokens(await this.#capture(host)),
193
- ...(persistence ? { persistence } : {}),
163
+ // Captured on first use, re-captured on a 401 (no refresh grant), expiring
164
+ // at the JWT's `exp`.
165
+ const mgr = createCapturedTokenManager({
166
+ capture: () => this.#capture(host),
167
+ persistence: this.#cache?.forHost(host) ?? null,
194
168
  });
195
169
  this.#managers.set(host, mgr);
196
170
  return mgr;
@@ -28,9 +28,9 @@
28
28
  * `sharepoint-auth.ts` is, so a server run with `TEAMS_DISABLE_FETCHPROXY`
29
29
  * never has to load the bridge to boot.
30
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';
31
+ import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
32
+ import { captureWindowMs } from './capture-window.js';
33
+ import { createCaptureTransport, getWsPort } from './auth-fetchproxy.js';
34
34
  import { PACKAGE_NAME, VERSION } from './version.js';
35
35
  /** The one request we capture from: a search-service call the Teams tab makes. */
36
36
  export const SUBSTRATE_CAPTURE_DECL = {
@@ -46,59 +46,26 @@ export const SUBSTRATE_CAPTURE_DECL = {
46
46
  * back to the client-side scan.
47
47
  */
48
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
49
  /**
52
50
  * Capture a Substrate search token from the user's signed-in Teams tab.
53
51
  * Returns the bare token (no `Bearer ` prefix).
54
52
  */
55
53
  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({
54
+ return captureBearerHeader({
59
55
  // Same verb set as the other two captures (`capture_request_header` beside
60
56
  // the always-on `fetch`); only the trusted domain differs.
61
- ...createBootstrapOpts({
62
- domains: [...SUBSTRATE_TRUST_DOMAINS],
63
- bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] },
64
- }),
57
+ captures: [SUBSTRATE_CAPTURE_DECL],
58
+ domains: SUBSTRATE_TRUST_DOMAINS,
59
+ // Read per capture, not at import: see `capture-window.ts`.
60
+ windowMs: captureWindowMs(env),
65
61
  port: getWsPort(),
66
- fetchTimeoutMs: bridgeDeadlineMs(windowMs),
67
- captureWindowMs: windowMs,
68
62
  serverName: PACKAGE_NAME,
69
63
  version: VERSION,
64
+ what: 'a Substrate search token',
65
+ guidance: 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
66
+ 'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
67
+ 'is read from — then retry. A "not in declared set" error means the ContextMint Bridge ' +
68
+ 'pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.',
69
+ createTransport: createCaptureTransport,
70
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
71
  }
@@ -1,4 +1,4 @@
1
- import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
1
+ import { createFileStatePersistence, isBearerTokens, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
2
  import { parseBoolEnv } from '@chrischall/mcp-utils';
3
3
  import { reportCacheWriteFailure } from './token-cache.js';
4
4
  /**
@@ -16,16 +16,6 @@ export function substrateTokenCachePath(env = process.env) {
16
16
  fileName: 'substrate-token.json',
17
17
  });
18
18
  }
19
- /** Same `BearerTokens` guard as the other caches; copied, as it is module-private there. */
20
- function isToken(raw) {
21
- if (raw === null || typeof raw !== 'object')
22
- return false;
23
- const t = raw;
24
- return (typeof t.accessToken === 'string' &&
25
- t.accessToken !== '' &&
26
- typeof t.expiresAt === 'number' &&
27
- (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
28
- }
29
19
  /**
30
20
  * The Substrate token cache, or `null` when it is off or there is nothing to
31
21
  * cache. Gated like the SharePoint cache: `TEAMS_TOKEN_CACHE` (default on), and
@@ -40,7 +30,7 @@ export function createSubstrateTokenCache(env = process.env) {
40
30
  const file = createFileStatePersistence({
41
31
  filePath: substrateTokenCachePath(env),
42
32
  boundTo: 'fetchproxy',
43
- validate: (raw) => (isToken(raw) ? raw : null),
33
+ validate: (raw) => (isBearerTokens(raw) ? raw : null),
44
34
  });
45
35
  return {
46
36
  load: () => file.load(),