dsh-mcp 1.14.2 → 1.14.4

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/CHANGELOG.en.md CHANGED
@@ -12,6 +12,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
12
12
  - **Supported DSH version**: **dsh `0.2.0-rc.2`** — the latest release is developed and verified on `0.2.0-rc.2` (declared in `package.json` → `dsh.supported`); older entries state the version verified at their time. When the DSH and plugin versions do not match, the Settings page reports a diagnosis (check whether the bundle is selected → restart `dsh web` → hard-refresh → upgrade both sides).
13
13
  - **Release convention**: every version entry states `- **Supported DSH version**: dsh <version>`, mirrored in the GitHub Release notes. The release body is written in **Chinese** (matching [CHANGELOG.md](CHANGELOG.md)), with heading levels mirroring the entry.
14
14
 
15
+ ## [1.14.4] - 2026-11-03
16
+
17
+ - **Supported DSH version**: **dsh `0.2.0-rc.2`**
18
+
19
+ ### Fixed
20
+
21
+ - **OAuth authorization died every hour and always asked to re-authorize (the provider wiped credentials when the access token expired)**: as soon as the access token's JWT `exp` had passed, `tokens()` deleted the whole credential — including a still-valid refresh token — and reported "no token", so the MCP SDK could never reach `refreshAuthorization` and always fell back to authorizing again; the tool-call guard in `lib/mcp-client.js` treated an expired access token as "needs authorization" too. Net effect: once a ~1h access token expired, a mount or tool call reopened the browser or demanded re-authorization, even though the server had handed out a perfectly usable refresh token. Now `tokens()` returns the stored credential whenever a refresh token exists, which lets the SDK's "401 → silent refresh → one retry" path run; only an expired credential **without** a refresh token is cleared for a fresh authorization. The same change keeps `oauthTokenStatus` (the settings-page state) reporting "authorized" while only the refresh token is left, instead of dropping back to "not authorized" every hour. A revoked/expired refresh token still goes through the SDK's `InvalidGrant` branch (clear + re-authorize), unchanged. The README's never-quite-true "auto-renewed while active within 24h" claim is corrected as well
22
+
23
+ ### Notes
24
+
25
+ - New `test/oauth-refresh.test.mjs` (needs the DSH module closure, so it runs only where a DSH installation is present): the fake authorization server supports the `refresh_token` grant and covers (1) expired access token + refresh token → silent refresh (exactly one `grant_type=refresh_token` request, no interactive authorization, refreshed tokens persisted with a future expiry), (2) expired without a refresh token → cleared and re-authorization required, (3) `oauthTokenStatus` still reporting authorized with only a refresh token. All three failed before the fix (the old code also really bound a loopback listener in the test, so the regression test now intercepts the redirect to fail fast)
26
+ - Host side only (`lib/oauth.js`, `lib/mcp-client.js`, docs): the client bundle `lib/client.js` and every Remote interface are untouched, so no rebuild is needed after upgrading
27
+
28
+ ## [1.14.3] - 2026-10-31
29
+
30
+ - **Supported DSH version**: **dsh `0.2.0-rc.2`**
31
+
32
+ ### Fixed
33
+
34
+ - **Authorization fails after the browser already reports success when the authorization server advertises RFC 9207 `iss` support but never sends `iss` ([#18](https://github.com/ArvinQi/dsh-mcp/issues/18))**: Notion's authorization-server metadata (`https://mcp.notion.com/.well-known/oauth-authorization-server`) says `authorization_response_iss_parameter_supported: true`, yet its real callback URL carries **no** `iss` parameter. MCP SDK 2.0.0's `validateAuthorizationResponseIssuer()` reads "advertised + absent" as an authorization-server mix-up attack and throws `IssuerMismatchError`, so the browser shows a successful authorization while the plugin reports `Issuer mismatch in authorization response (RFC 9207): expected "https://mcp.notion.com", received undefined` — with no way around it until the server fixes its metadata. Two changes in `lib/oauth.js`: (1) the `iss` from the callback URL is now handed to `exchangeAuthorization()` as-is — it used to be **dropped**, so the SDK only ever saw `undefined` and that was wrong in both directions: a server that advertises support *and* sends the correct `iss` was also rejected, while a **mix-up response carrying a wrong `iss` from a non-advertising server was silently accepted**; (2) only when the callback really carries no `iss` and the metadata claims support is that one claim removed (from a copy, so registration/authorization-URL construction see the original) before the token exchange, with one warning logged — RFC 9207 makes `iss` OPTIONAL, so an absent value is not by itself an attack signal, the advertisement is simply inaccurate for this response. A callback that does carry `iss` still goes through the SDK's strict string comparison and still throws on a mismatch. Both the settings-page / tool-auth callback listener and the legacy no-`serverUrl` fallback listener are fixed
35
+
36
+ ### Notes
37
+
38
+ - Three regression cases added to `test/oauth-flow.test.mjs` (that file needs the DSH module closure, so it runs only where a DSH installation is present): (1) advertises support but sends no `iss` → authorizes (the #18 reproduction, which failed before the fix); (2) callback with the correct `iss` → authorizes (also failed before the fix: with the parameter dropped, validation saw `undefined`); (3) callback with a wrong `iss` → still rejected with `Issuer mismatch` and no tokens stored
39
+ - Host-side `lib/oauth.js` only: the client bundle `lib/client.js` and every Remote interface are untouched, so no rebuild is needed after upgrading
40
+
15
41
  ## [1.14.2] - 2026-10-29
16
42
 
17
43
  - **Supported DSH version**: **dsh `0.2.0-rc.2`**
package/CHANGELOG.md CHANGED
@@ -12,6 +12,32 @@
12
12
  - **支持版本**:**dsh `0.2.0-rc.2`** —— 最新版本在 `0.2.0-rc.2` 上开发与验证(`package.json` → `dsh.supported` 同步声明);历史版本条目各自声明当时验证的版本。DSH 与插件版本不匹配时,设置页会给出排查诊断(核对 bundle 是否已选中 → 重启 `dsh web` → 硬刷新 → 同步升级)。
13
13
  - **发版约定**:每个版本条目都要声明 `- **支持版本**:dsh <版本>`,并在 GitHub Release notes 中同步。Release 正文用**中文**(与本文档一致),标题层级与条目一致。
14
14
 
15
+ ## [1.14.4] - 2026-11-03
16
+
17
+ - **支持版本**:**dsh `0.2.0-rc.2`**
18
+
19
+ ### 修复
20
+
21
+ - **OAuth 授权每小时失效、每次都要重新授权(provider 在 access token 过期时提前清库)**:`tokens()` 一发现 access token 的 JWT `exp` 已过,就把整份凭据——包括仍然有效的 refresh token——从凭据文档里删掉并返回「没有 token」,于是 MCP SDK 永远走不到 `refreshAuthorization`,只会走「重新授权」;工具调用侧 `lib/mcp-client.js` 的守卫同样把「access token 过期」直接当成需要授权。结果是:约 1 小时有效期的 access token 一到点,挂载 / 工具调用就重新弹浏览器或提示「需要授权」,而服务端其实一直发着可用的 refresh token。现在:只要还有 refresh token,`tokens()` 就原样交回凭据,让 SDK 的「401 → 静默刷新 → 重试一次」链路生效;只有「已过期且没有 refresh token」才清库、要求重新授权。同处修正让 `oauthTokenStatus`(设置页状态)在仅剩 refresh token 时仍报告已授权,不再每小时退回「未授权」。refresh token 被吊销或过期时,SDK 的 `InvalidGrant` 分支照旧清凭据并重新授权,行为不变。顺带修正 README 里「24 小时内活跃自动续期」这句从未真正成立的描述
22
+
23
+ ### 说明
24
+
25
+ - 新增 `test/oauth-refresh.test.mjs`(依赖 DSH 模块闭包,仅在装有 DSH 的环境执行):假授权服务器支持 `refresh_token` 授权,覆盖 ① access token 过期 + 有 refresh token → SDK 静默刷新(只发一次 `grant_type=refresh_token`、不进入交互式授权、新 token 落库且过期时间在未来);② 过期且没有 refresh token → 清库并要求重新授权;③ `oauthTokenStatus` 对「仅剩 refresh token」仍报已授权。修复前这三个用例全部失败(且旧实现会在测试里真的去开回环监听,现已用重定向拦截让回归快速失败)
26
+ - 只改宿主侧 `lib/oauth.js`、`lib/mcp-client.js` 与文档:客户端包 `lib/client.js` 与所有 Remote 接口未变,升级后无需重新构建产物
27
+
28
+ ## [1.14.3] - 2026-10-31
29
+
30
+ - **支持版本**:**dsh `0.2.0-rc.2`**
31
+
32
+ ### 修复
33
+
34
+ - **授权服务器「声明支持 RFC 9207 `iss` 却不在回调里带」时,浏览器已显示授权成功、插件仍判失败([#18](https://github.com/ArvinQi/dsh-mcp/issues/18))**:Notion 的授权服务器元数据(`https://mcp.notion.com/.well-known/oauth-authorization-server`)写着 `authorization_response_iss_parameter_supported: true`,但真实的回调 URL 里**没有** `iss` 参数;MCP SDK 2.0.0 的 `validateAuthorizationResponseIssuer()` 把「声明支持 + 回调缺失」直接当作授权服务器混同攻击并抛 `IssuerMismatchError`,于是浏览器页面上授权已经成功、插件侧却报 `Issuer mismatch in authorization response (RFC 9207): expected "https://mcp.notion.com", received undefined`,在服务端修好元数据之前无法绕过。修复包含两点(`lib/oauth.js`):① 回调 URL 里的 `iss` 现在会原样交给 `exchangeAuthorization()`——此前它被**丢弃**,SDK 只能拿到 `undefined`,于是反过来两头都错:「声明支持 `iss` 且确实回了正确 `iss` 的服务器」照样被判失败,「没声明支持、却带回错误 `iss` 的混同响应」反倒被静默放行;② 只有当回调**确实没带** `iss`、而元数据又声明支持时,才把这一条声明从交给令牌交换的元数据**副本**上去掉,并打一条 warning 日志(RFC 9207 中 `iss` 本就是可选参数,缺失本身不是攻击信号,声明只是与本次响应不符)。带着 `iss` 的回调仍走 SDK 的严格字符串比对,`iss` 与 `metadata.issuer` 不一致照样抛错;设置页 / tool-auth 的回调监听器与「无 serverUrl」的旧版兜底监听器两条路径都已修正
35
+
36
+ ### 说明
37
+
38
+ - 新增 3 个回归用例到 `test/oauth-flow.test.mjs`(该文件依赖 DSH 模块闭包,只在本地装有 DSH 的环境执行):① 声明支持但回调不带 `iss` → 授权成功(#18 的复现,修复前失败);② 回调带正确的 `iss` → 授权成功(修复前同样失败:`iss` 被丢弃后校验看到的是 `undefined`);③ 回调带错误的 `iss` → 仍然拒绝并报 `Issuer mismatch`,且不落任何 token
39
+ - 本次只改宿主侧 `lib/oauth.js`:客户端包 `lib/client.js` 与所有 Remote 接口未变,升级后无需重新构建产物
40
+
15
41
  ## [1.14.2] - 2026-10-29
16
42
 
17
43
  - **支持版本**:**dsh `0.2.0-rc.2`**
package/README.en.md CHANGED
@@ -23,7 +23,7 @@
23
23
  - **Image result passthrough**: images returned by MCP tools (screenshots/charts) are projected through the attachment service into model image context, with strict preflight and bounded fallbacks (PR #4)
24
24
  - **Two injection modes**: `search` (on-demand, token-saving) and `full` (inject everything)
25
25
  - **Zero npm dependencies**: plugs into DeepSeek Harness internals, install and go
26
- - **OAuth authentication**: for `streamable-http` servers using MCP OAuth (authorization-code + PKCE), the server card has an **Authorize** button and the **Host opens the system browser** for the login; the page then polls the authorization status every 5 seconds. Tokens and OAuth client info are persisted and refreshed automatically by the SDK (auto-renewed while active within 24h), with re-authorization after expiry. **Before you authorize it only says "authorizing"; a real failure reports its reason**
26
+ - **OAuth authentication**: for `streamable-http` servers using MCP OAuth (authorization-code + PKCE), the server card has an **Authorize** button and the **Host opens the system browser** for the login; the page then polls the authorization status every 5 seconds. Tokens and OAuth client info are persisted in the credentials document; when the access token expires the SDK **renews it silently** with the stored refresh token (no interruption, no browser), and only a revoked/expired refresh token needs re-authorization. **Before you authorize it only says "authorizing"; a real failure reports its reason**
27
27
  - **HTTPS verified against the system trust store by default**: intranet/corporate CAs (roots installed in the OS keychain) no longer need `NODE_OPTIONS=--use-system-ca` on `dsh web`; the plugin merges the OS store into Node's default root store at startup
28
28
  - **Three install paths**: npm / GitHub git source / local link; bilingual UI and docs
29
29
 
@@ -271,6 +271,20 @@ Check in order:
271
271
  in the OS keychain, or fall back to `NODE_OPTIONS=--use-system-ca` / `NODE_EXTRA_CA_CERTS`, then
272
272
  restart the host and hard-refresh.
273
273
 
274
+ **Q5: The browser already shows a successful authorization, but the plugin reports `Issuer mismatch in authorization response (RFC 9207)`?**
275
+
276
+ - The authorization server's metadata does not match its behaviour: it advertises
277
+ `authorization_response_iss_parameter_supported: true` in
278
+ `/.well-known/oauth-authorization-server`, yet its callback URL carries no `iss` parameter (Notion's
279
+ `https://mcp.notion.com` does exactly this — see
280
+ [#18](https://github.com/ArvinQi/dsh-mcp/issues/18)). Such an inaccurate claim is tolerated **since
281
+ 1.14.3**: the claim is ignored, with a warning in the log, only when the callback
282
+ really carries no `iss`, while a callback that does carry `iss` is still compared strictly. Upgrade and
283
+ restart `dsh web`, then click "Authorize with OAuth" once more;
284
+ - If the log line instead shows a callback that carried an `iss` differing from the metadata `issuer`,
285
+ that is **not** a metadata problem but a genuine authorization-server mix-up risk, still rejected per
286
+ RFC 9207 — check that the MCP server URL and the authorization server really belong together.
287
+
274
288
  **Add a server**:
275
289
 
276
290
  1. Click **Add server** (the form expands inline above the list).
@@ -311,9 +325,11 @@ Check in order:
311
325
  - On success the button disappears and the tools appear; a failure reports its reason (e.g.
312
326
  "authorization failed: access_denied"), and an expired callback says "authorization did not complete
313
327
  (retry)". Nothing is reported as failed before you authorize.
314
- - Tokens and the registered OAuth client are persisted in the credentials document (scoped by `serverName`)
315
- and refreshed automatically by the MCP SDK (auto-renewed while active within 24h); after authorizing once,
316
- mounts and later test connections reuse the same token, and an expired token triggers a fresh
328
+ - Tokens and the registered OAuth client are persisted in the credentials document (scoped by `serverName`).
329
+ When the access token (typically ~1h) expires, the SDK **refreshes it silently with the stored refresh
330
+ token and retries the request** — no re-authorization; only a revoked/expired refresh token, or a server
331
+ that issues none, falls back to authorizing again. After authorizing once, mounts and later test
332
+ connections reuse the same token, and an unrefreshable expired token triggers a fresh
317
333
  authorization automatically.
318
334
  - A server that is already live and serving tools (its static token is enough) is not flagged red; the red
319
335
  badge/button is reserved for servers the missing authorization actually blocks.
package/README.md CHANGED
@@ -25,7 +25,7 @@
25
25
  - **图片结果透传**:MCP 工具返回的图片(截图/图表等)经附件服务投影为图片引用进入模型上下文,带严格预检与有界降级文案(PR #4)
26
26
  - **双注入模式**:`search`(按需检索,省 token)与 `full`(全量注入)
27
27
  - **零 npm 依赖**:直接对接 DeepSeek Harness 内部能力,安装即用
28
- - **OAuth 认证支持**:`streamable-http` 服务器若走 MCP OAuth(授权码 + PKCE),服务器卡片点「OAuth 授权」按钮,**由宿主打开系统浏览器**完成授权,本页每 5 秒轮询授权状态;token 与 client 信息持久化、由 SDK 自动刷新(24 小时内活跃自动续期),失效后重新授权。**授权完成前只显示「授权中」,授权失败会写明原因**
28
+ - **OAuth 认证支持**:`streamable-http` 服务器若走 MCP OAuth(授权码 + PKCE),服务器卡片点「OAuth 授权」按钮,**由宿主打开系统浏览器**完成授权,本页每 5 秒轮询授权状态;token 与 client 信息持久化在凭据文档;access token 过期后由 SDK 用存储的 refresh token **静默续期**(不会打断使用、也不会再弹浏览器),只有 refresh token 也被吊销/过期时才需要重新授权。**授权完成前只显示「授权中」,授权失败会写明原因**
29
29
  - **HTTPS 默认按系统证书校验**:内网/公司 CA(只装在系统钥匙串里的根证书)无需再给 `dsh web` 加 `NODE_OPTIONS=--use-system-ca`,插件启动时把系统信任库并入 Node 默认根证书库
30
30
  - **三种安装方式**:npm / GitHub git 源 / 本地 link;中英文界面与文档
31
31
 
@@ -263,6 +263,17 @@ dsh plugin --profile web add link:<本仓库绝对路径>
263
263
  系统证书说明),通常无需额外配置;仍失败时再检查系统钥匙串里是否装了该根证书,或临时用
264
264
  `NODE_OPTIONS=--use-system-ca` / `NODE_EXTRA_CA_CERTS` 启动 `dsh web` 兜底,并重启宿主与硬刷新浏览器。
265
265
 
266
+ **Q5:浏览器里已经显示授权成功,插件却报 `Issuer mismatch in authorization response (RFC 9207)`?**
267
+
268
+ - 这是授权服务器的元数据与真实行为不一致:它在 `/.well-known/oauth-authorization-server` 里声明
269
+ `authorization_response_iss_parameter_supported: true`,但回调 URL 里并不带 `iss` 参数
270
+ (Notion 的 `https://mcp.notion.com` 就是如此,见 [#18](https://github.com/ArvinQi/dsh-mcp/issues/18))。
271
+ 该不实声明自 **1.14.3** 起已自动容忍:只有当回调确实没带 `iss` 时,才忽略该声明并打一条
272
+ warning 日志,带 `iss` 的回调仍会严格比对;升级并重启 `dsh web` 后,重新点一次
273
+ 「OAuth 授权」即可;
274
+ - 若日志里的 warning 显示回调带了 `iss` 但与元数据 `issuer` 不一致,那**不是**元数据问题,而是真正的
275
+ 授权服务器混同风险,按 RFC 9207 仍会拒绝——请核对 MCP 服务器 URL 与授权服务器是否配对。
276
+
266
277
  **添加服务器**:
267
278
 
268
279
  1. 点击「添加服务器」(表单在列表上方就地展开)
@@ -294,8 +305,9 @@ dsh plugin --profile web add link:<本仓库绝对路径>
294
305
  行上显示「授权中…」并**每 5 秒检查一次授权状态**;浏览器没起来时可以点行内的手动链接
295
306
  - 授权成功后按钮消失、工具出现;失败会写明原因(如「授权失败: access_denied」),
296
307
  回调消失则显示「授权未完成(可重试)」——授权完成前不会报失败
297
- - token 与 OAuth client 信息持久化在凭据文档(按 `serverName` 隔离),由 MCP SDK 自动刷新
298
- (24 小时内活跃自动续期);失效后重新授权,授权一次后挂载与测试复用
308
+ - token 与 OAuth client 信息持久化在凭据文档(按 `serverName` 隔离);access token(通常约 1 小时)
309
+ 过期时,SDK 用存储的 refresh token **静默刷新并重试原请求**,不需要重新授权——只有 refresh token
310
+ 被吊销/过期,或服务端根本没发 refresh token 时,才会回到「重新授权」这一步;授权一次后挂载与测试复用
299
311
  - 已经 `live` 且有工具的服务器(静态 token 够用)不会被打上红色「未授权」,只保留一个普通授权按钮;
300
312
  红色徽标/红色按钮只用于授权确实卡住挂载的服务器
301
313
  - 第一次挂载(`allowBrowserOnMount`,默认开)仍可能自动弹一次浏览器;把 profile 的
package/lib/mcp-client.js CHANGED
@@ -292,13 +292,17 @@ function createOutput(rawName, structuredSchema) {
292
292
  function createExecutor(client, ctx, rawName, taskRequired, opts, projections) {
293
293
  return async (args, exec) => {
294
294
  if (taskRequired) throw new Error(`Tool "${rawName}" requires task-based execution, which this bridge does not support`);
295
- // OAuth servers: if the stored token is missing or expired, do NOT let
296
- // the SDK open a browser from inside a tool call (a session could open
297
- // several tabs at once). Instead, build an authorization URL and return
298
- // it for the user to click; a background listener completes the flow.
295
+ // OAuth servers: a tool call must never START an interactive browser
296
+ // authorization (a session could open several tabs at once), so a
297
+ // credential that cannot refresh gets a click-to-authorize link instead.
298
+ // An expired access token is no longer that case: the SDK refreshes
299
+ // silently (401 → refreshAuthorization → one retry) whenever a refresh
300
+ // token is stored, so demanding re-authorization here would break every
301
+ // token lifetime (~1h access tokens).
299
302
  if (opts.authProvider !== void 0 && opts.authProvider.tokens !== void 0) {
300
303
  const tokens = await opts.authProvider.tokens();
301
- const expired = tokens === void 0 || tokens.access_token === void 0 || (() => {
304
+ const refreshable = tokens !== void 0 && tokens.refresh_token !== void 0 && tokens.refresh_token !== null && tokens.refresh_token !== "";
305
+ const accessTokenExpired = tokens !== void 0 && tokens.access_token !== void 0 && (() => {
302
306
  try {
303
307
  const payload = JSON.parse(Buffer.from(String(tokens.access_token).split(".")[1] ?? "", "base64url").toString("utf8"));
304
308
  return typeof payload.exp === "number" && Date.now() / 1000 >= payload.exp;
@@ -306,7 +310,10 @@ function createExecutor(client, ctx, rawName, taskRequired, opts, projections) {
306
310
  return false;
307
311
  }
308
312
  })();
309
- if (expired) {
313
+ const needsAuthorization = tokens === void 0
314
+ ? true
315
+ : !refreshable && (tokens.access_token === void 0 || accessTokenExpired);
316
+ if (needsAuthorization) {
310
317
  try {
311
318
  const authUrl = await createToolAuthorizationUrl(opts.serverName, ctx, opts.url);
312
319
  throw oauthRequiredError(hostText(ctx, "oauthToolLink", { serverName: opts.serverName, url: authUrl }));
package/lib/oauth.js CHANGED
@@ -127,6 +127,46 @@ function jwtExp(accessToken) {
127
127
  }
128
128
  }
129
129
 
130
+ /**
131
+ * Prepare authorization-server metadata for the RFC 9207 check that the MCP
132
+ * SDK runs when an authorization code is redeemed, tolerating a server whose
133
+ * advertisement is not honoured.
134
+ *
135
+ * `validateAuthorizationResponseIssuer()` throws `IssuerMismatchError` when the
136
+ * metadata advertises `authorization_response_iss_parameter_supported: true`
137
+ * and the callback URL carries no `iss` parameter — the SDK reads that
138
+ * combination as an authorization-server mix-up attack. Some servers advertise
139
+ * the parameter and then never send it (Notion's `https://mcp.notion.com`,
140
+ * issue #18), so every attempt fails with
141
+ *
142
+ * Issuer mismatch in authorization response (RFC 9207): expected "…", received undefined
143
+ *
144
+ * right after the browser has already shown the success page. RFC 9207 makes
145
+ * `iss` OPTIONAL, so an absent value is not by itself evidence of an attack;
146
+ * the advertisement is simply inaccurate for this response.
147
+ *
148
+ * When — and only when — the callback really came without `iss`, drop that one
149
+ * claim from the metadata handed to the exchange, and say so in the log. A
150
+ * callback that does carry `iss` keeps the SDK's strict
151
+ * `iss === metadata.issuer` comparison, so mix-up protection is unchanged for
152
+ * servers that implement RFC 9207. The claim is cleared on a copy because the
153
+ * discovered document is shared with client registration and with building the
154
+ * authorization URL.
155
+ *
156
+ * @param metadata - discovered authorization-server metadata.
157
+ * @param iss - the `iss` parameter from the callback, when one was sent.
158
+ * @param log - caller logger, for the one-line diagnostic.
159
+ * @param tag - log prefix carrying the server id.
160
+ * @returns the metadata to pass to `exchangeAuthorization`.
161
+ */
162
+ function metadataForAuthorizationResponse(metadata, iss, log, tag) {
163
+ if (metadata === undefined || metadata === null) return metadata;
164
+ if (iss !== undefined) return metadata;
165
+ if (metadata.authorization_response_iss_parameter_supported !== true) return metadata;
166
+ log.warn?.(`${tag}: authorization server advertises RFC 9207 iss support but the callback carried no iss; ignoring the claim for this exchange`);
167
+ return { ...metadata, authorization_response_iss_parameter_supported: undefined };
168
+ }
169
+
130
170
  /**
131
171
  * Derive a stable loopback port from the server id. The redirect URI must
132
172
  * stay identical across processes because the registered OAuth client's
@@ -245,15 +285,24 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
245
285
  } catch {
246
286
  return undefined;
247
287
  }
248
- // An expired access token makes the SDK try refresh; if the refresh
249
- // token is also dead (short-lived servers), the SDK throws
250
- // InvalidTokenError and never re-authorizes. Pre-expire it here so the
251
- // SDK falls through to a fresh browser authorization flow instead.
252
- const exp = jwtExp(tokens.access_token);
253
- if (exp !== undefined && Date.now() / 1000 >= exp) {
254
- log.info(`${tag}: stored access token expired, clearing for re-authorization`);
255
- await ctx.credentials.unset(oauthTokenRef(serverId));
256
- return undefined;
288
+ // An expired access token is NOT a reason to forget the credentials: the
289
+ // SDK answers a 401 with `refreshAuthorization` and retries the request,
290
+ // and that path only runs when the stored tokens (refresh token included)
291
+ // are handed back. Clearing on expiry — the previous behaviour — turned
292
+ // every token lifetime into a fresh browser authorization although the
293
+ // refresh token was still valid (access tokens here live ~1h). Only a
294
+ // credential that cannot refresh at all is dropped, so the SDK goes
295
+ // straight to the authorization flow instead of a doomed refresh; a dead
296
+ // refresh token is handled by `auth()` itself (InvalidGrant →
297
+ // invalidateCredentials → retry → browser flow).
298
+ const refreshable = tokens.refresh_token !== undefined && tokens.refresh_token !== null && tokens.refresh_token !== "";
299
+ if (!refreshable) {
300
+ const exp = jwtExp(tokens.access_token);
301
+ if (exp !== undefined && Date.now() / 1000 >= exp) {
302
+ log.info(`${tag}: stored access token expired and no refresh token is stored, clearing for re-authorization`);
303
+ await ctx.credentials.unset(oauthTokenRef(serverId));
304
+ return undefined;
305
+ }
257
306
  }
258
307
  return tokens;
259
308
  },
@@ -332,6 +381,9 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
332
381
  const url = new URL(req.url, redirectUrl);
333
382
  const code = url.searchParams.get("code");
334
383
  const error = url.searchParams.get("error");
384
+ // RFC 9207: keep the issuer the server sent, so the SDK can compare
385
+ // it strictly at exchange time instead of us dropping it silently.
386
+ const iss = url.searchParams.get("iss") ?? undefined;
335
387
  res.setHeader("content-type", "text/html; charset=utf-8");
336
388
  // No keep-alive: the stable port may be reused by the next flow (see
337
389
  // closeCallbackServer).
@@ -345,7 +397,7 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
345
397
  }
346
398
  res.end(hostText(ctx, "oauthOkPage"));
347
399
  log.info(`${tag}: authorization callback received (code)`);
348
- resolveResult({ code });
400
+ resolveResult({ code, iss });
349
401
  });
350
402
  server.on("error", (error) => {
351
403
  log.error(`${tag}: callback server error: ${error instanceof Error ? error.message : String(error)}`);
@@ -368,9 +420,10 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
368
420
  const clientInformation = await this.clientInformation();
369
421
  const codeVerifier = await this.codeVerifier();
370
422
  const tokens = await exchangeAuthorization(authServerUrl, {
371
- metadata,
423
+ metadata: metadataForAuthorizationResponse(metadata, result.iss, log, tag),
372
424
  clientInformation,
373
425
  authorizationCode: result.code,
426
+ iss: result.iss,
374
427
  codeVerifier,
375
428
  redirectUri: redirectUrl,
376
429
  fetchFn: systemFetch(),
@@ -527,6 +580,9 @@ async function createToolAuthorizationUrlOnce(serverId, ctx, serverUrl) {
527
580
  const callbackUrl = new URL(req.url, redirectUrl);
528
581
  const code = callbackUrl.searchParams.get("code");
529
582
  const error = callbackUrl.searchParams.get("error");
583
+ // RFC 9207: keep the issuer the server sent, so the SDK can compare it
584
+ // strictly at exchange time instead of us dropping it silently.
585
+ const iss = callbackUrl.searchParams.get("iss") ?? undefined;
530
586
  res.setHeader("content-type", "text/html; charset=utf-8");
531
587
  // Never keep the callback connection alive: the stable loopback port is
532
588
  // reused by the next flow, and a pooled keep-alive socket would deliver
@@ -547,9 +603,10 @@ async function createToolAuthorizationUrlOnce(serverId, ctx, serverUrl) {
547
603
  const authServerUrl = new URL(authorizationUrl.origin);
548
604
  const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { fetchFn: systemFetch() });
549
605
  const tokens = await exchangeAuthorization(authServerUrl, {
550
- metadata,
606
+ metadata: metadataForAuthorizationResponse(metadata, iss, log, tag),
551
607
  clientInformation: clientInfo,
552
608
  authorizationCode: code,
609
+ iss,
553
610
  codeVerifier,
554
611
  redirectUri: redirectUrl,
555
612
  fetchFn: systemFetch(),
@@ -606,13 +663,17 @@ export function isOAuthRequired(error) {
606
663
  }
607
664
 
608
665
  /**
609
- * The stored-token state of one server, without touching the network. An
610
- * expired access token counts as not authorized (the provider clears it so the
611
- * SDK starts a fresh browser flow), which is what a polling settings page must
612
- * see before showing "authorization complete".
666
+ * The stored-token state of one server, without touching the network. A stored
667
+ * refresh token counts as authorized even after the access token's JWT `exp`
668
+ * has passed: the SDK refreshes silently on the next 401 (`refreshAuthorization`
669
+ * plus one retry), so a polling settings page must not fall back to "needs
670
+ * authorization" every hour. Only a credential that cannot refresh is
671
+ * unauthorized.
613
672
  * @param serverId - managed server id / server name the tokens are keyed by.
614
673
  * @param ctx - host context carrying the credentials service.
615
- * @returns `authorized`, plus the JWT expiry (ms) when one is known.
674
+ * @returns `authorized`, plus the access-token JWT expiry (ms) when one is
675
+ * known and still meaningful (omitted when only a refresh token keeps the
676
+ * credential alive — the next refresh decides the new expiry).
616
677
  */
617
678
  export async function oauthTokenStatus(serverId, ctx) {
618
679
  let hit;
@@ -629,7 +690,10 @@ export async function oauthTokenStatus(serverId, ctx) {
629
690
  return { authorized: false };
630
691
  }
631
692
  const exp = jwtExp(tokens?.access_token);
632
- if (exp !== undefined && Date.now() / 1000 >= exp) return { authorized: false, expiresAt: exp * 1000 };
693
+ const refreshable = tokens?.refresh_token !== undefined && tokens?.refresh_token !== null && tokens.refresh_token !== "";
694
+ const expired = exp !== undefined && Date.now() / 1000 >= exp;
695
+ if (expired && !refreshable) return { authorized: false, expiresAt: exp * 1000 };
696
+ if (expired) return { authorized: true };
633
697
  return { authorized: true, ...(exp === undefined ? {} : { expiresAt: exp * 1000 }) };
634
698
  }
635
699
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mcp",
3
- "version": "1.14.2",
3
+ "version": "1.14.4",
4
4
  "description": "MCP 管理界面 + tool search:可视化配置/启停/刷新 MCP 服务器与工具勾选,按需检索(tool search)热注入;工具列表稳定命中缓存、不撑爆上下文。DeepSeek Harness plugin: MCP management UI + tool search — stable tool list, cache-friendly, no context bloat.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
package/scripts/test.mjs CHANGED
@@ -28,6 +28,7 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
28
28
  const NEEDS_DSH_CLOSURE = new Set([
29
29
  'cordis-servers.test.mjs',
30
30
  'oauth-flow.test.mjs',
31
+ 'oauth-refresh.test.mjs',
31
32
  'patch-writer.test.mjs',
32
33
  'stdio-env.test.mjs',
33
34
  'takeover.test.mjs',