dsh-desktop-kit 2.7.10 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +19 -18
- package/client.js +44 -2
- package/docs/TEST-2.8.0.md +25 -0
- package/docs/TEST-2.9.0.md +28 -0
- package/package.json +2 -2
- package/plugins/dsh-agent-extensions/index.js +19 -0
- package/plugins/dsh-agent-extensions/lib/instructions.js +104 -0
- package/plugins/dsh-mcp-manager/README.md +17 -3
- package/plugins/dsh-mcp-manager/client.js +43 -1
- package/plugins/dsh-mcp-manager/lib/api.js +35 -1
- package/plugins/dsh-mcp-manager/lib/client.js +22 -1
- package/plugins/dsh-mcp-manager/lib/manager.js +22 -1
- package/plugins/dsh-mcp-manager/lib/oauth.js +368 -0
- package/plugins/dsh-mcp-manager/screenshots/oauth-1440.png +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.9.0 (2026-11-12)
|
|
4
|
+
|
|
5
|
+
- **Project instructions.** `AGENTS.md` и `CLAUDE.md` читаются иерархически: root → вложенные папки до cwd → `.dsh/AGENTS.md`; поддержан `@import`, лимиты глубины/размера/файлов, защита от выхода за проект и symlink-escape.
|
|
6
|
+
- **MCP roots.** HTTP/stdio MCP-сервер получает capability `roots` и ответ `roots/list` с корнем проекта; `ping` поддержан. Sampling/elicitation возвращают явный `-32601`, а не тихо игнорируются.
|
|
7
|
+
- **Тесты.** `instructions-tests`, обновлённый `mcp-manager-tests` (roots request/response).
|
|
8
|
+
- **Ограничение.** Sampling, elicitation, agent teams, marketplace, IDE bridge и OS sandbox в этот релиз не входят.
|
|
9
|
+
|
|
10
|
+
## 2.8.0 (2026-11-12)
|
|
11
|
+
|
|
12
|
+
- **MCP OAuth 2.1.** HTTP-серверы: protected-resource discovery (RFC 9728), AS metadata (RFC 8414/OIDC), dynamic client registration (RFC 7591), authorization code + PKCE S256, `state`, loopback callback, `resource`/audience binding, refresh, logout.
|
|
13
|
+
- **Token storage.** `~/.dsh/mcp.oauth.json` (0600), отдельно от `mcp.json`; токены не логируются; HTTPS обязателен вне localhost.
|
|
14
|
+
- **UI.** Кнопка «Войти»/«OAuth» у HTTP-сервера, статус OAuth в карточке, повторный consent; `oauth-start`, `oauth-status`, `oauth-logout`.
|
|
15
|
+
- **HTTP transport.** Автоматический `Authorization: Bearer` из token store с refresh за 60 секунд до истечения.
|
|
16
|
+
- **Тесты.** `mcp-oauth-tests`: discovery, DCR, PKCE, callback, token store, refresh, audience.
|
|
17
|
+
|
|
3
18
|
## 2.7.10 (2026-11-12)
|
|
4
19
|
|
|
5
20
|
- **Worktree hardening.** Managed worktrees всегда привязаны к главному worktree: запуск из вложенного worktree больше не создаёт nested `.dsh/worktrees`. Пути нормализуются, фильтрация идёт через `path.relative`.
|
package/README.md
CHANGED
|
@@ -4,17 +4,17 @@
|
|
|
4
4
|
|
|
5
5
|
Набор из **16 плагинов и 30 навыков** для DeepSeek Harness 0.2.x: русский интерфейс, автопилот навыков, токен-лаборатория, студия навыков, память проектов, обмен памятью между машинами (GitHub и USB), guardrails, карта репозитория, чекпоинты, plan mode, browser QA, GitHub review, Claude Code-подобные hooks/agents/commands, перенос чатов и резервные копии профиля.
|
|
6
6
|
|
|
7
|
-

|
|
8
8
|
|
|
9
9
|
## MCP: подключения без JSON
|
|
10
10
|
|
|
11
|
-
Настройки → **MCP**: пресеты GitHub, PostgreSQL и Filesystem, живые статусы, health, список tools и безопасное хранение токенов в `~/.dsh/mcp.secrets.json`. Промпты сервера открываются кнопкой **Prompts**: аргументы, запуск и копирование результата.
|
|
11
|
+
Настройки → **MCP**: пресеты GitHub, PostgreSQL и Filesystem, живые статусы, health, список tools и безопасное хранение токенов в `~/.dsh/mcp.secrets.json`. Промпты сервера открываются кнопкой **Prompts**: аргументы, запуск и копирование результата. HTTP-серверы подключаются через **OAuth 2.1 + PKCE** — токен хранится отдельно в `~/.dsh/mcp.oauth.json`.
|
|
12
12
|
|
|
13
|
-

|
|
14
14
|
|
|
15
|
-

|
|
16
16
|
|
|
17
|
-

|
|
18
18
|
|
|
19
19
|
## Права и субагенты
|
|
20
20
|
|
|
@@ -23,12 +23,13 @@
|
|
|
23
23
|
- **Approval** — штатная карточка DSH: Allow once / Always allow / Reject.
|
|
24
24
|
- **`.dsh/`** создаётся автоматически: agents, commands, rules, hooks, verify, mcp, PROJECT.md.
|
|
25
25
|
- **Worktrees и фоновые агенты.** `project_worktree` создаёт ветку `dsh/<slug>` и отдельную папку `.dsh/worktrees/<slug>`; `project_agent ... worktree=auto background=true` запускает агента в изоляции, а страница **Агенты** показывает worktrees и очередь запусков с кнопкой «Остановить».
|
|
26
|
+
- **Инструкции проекта.** `AGENTS.md` и `CLAUDE.md` читаются иерархически (root → вложенные папки → `.dsh`) с `@import`; MCP roots сообщает серверу корень проекта.
|
|
26
27
|
|
|
27
|
-

|
|
28
29
|
|
|
29
|
-

|
|
30
31
|
|
|
31
|
-
**v2.
|
|
32
|
+
**v2.9.0** · MIT · проверено на DSH `0.2.1-rc.5` и `0.2.2-rc.1` (Windows 11) · без внешних зависимостей и телеметрии
|
|
32
33
|
|
|
33
34
|
**План развития:** [docs/ROADMAP-3.0.md](docs/ROADMAP-3.0.md) — Memory Fabric, семантическое
|
|
34
35
|
слияние, локальный индекс памяти, шифрованные переносы, Memory Hub и npm trusted publishing.
|
|
@@ -116,27 +117,27 @@
|
|
|
116
117
|
- перед каждой синхронизацией проверяется, что репозиторий всё ещё приватный;
|
|
117
118
|
- секреты и PII вычищаются, домашние пути заменяются токеном `%DSH_HOME%`; LLM не вызывается — **0 токенов**.
|
|
118
119
|
|
|
119
|
-

|
|
120
121
|
|
|
121
|
-

|
|
122
123
|
|
|
123
124
|
## Скриншоты
|
|
124
125
|
|
|
125
126
|
### Skills Studio: каталог, стоимость и редактор
|
|
126
127
|
|
|
127
|
-

|
|
128
129
|
|
|
129
|
-

|
|
130
131
|
|
|
131
132
|
### Token Lab: куда уходит контекст
|
|
132
133
|
|
|
133
|
-

|
|
134
135
|
|
|
135
136
|
### Тёмная тема и мобильный
|
|
136
137
|
|
|
137
|
-

|
|
138
139
|
|
|
139
|
-

|
|
140
141
|
|
|
141
142
|
## Окно-напоминание: пиковый тариф
|
|
142
143
|
|
|
@@ -146,11 +147,11 @@ DeepSeek включает двойной тариф в пиковые часы (
|
|
|
146
147
|
- **в окне** — красная карточка: причина, границы окна в местном времени и UTC, живой отсчёт до конца и рекомендация, когда вернуться;
|
|
147
148
|
- **после окна** — карточка исчезает; состояние всегда доступно через `window.__DSH_PEAK_GUARD__.state()`.
|
|
148
149
|
|
|
149
|
-

|
|
150
151
|
|
|
151
|
-

|
|
152
153
|
|
|
153
|
-

|
|
154
155
|
|
|
155
156
|
Подробности и настройки — [plugins/dsh-peak-guard/README.md](plugins/dsh-peak-guard/README.md).
|
|
156
157
|
|
package/client.js
CHANGED
|
@@ -6912,6 +6912,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
6912
6912
|
.mcp-dot.err{background:#dc2626;box-shadow:0 0 0 3px rgba(220,38,38,.12)}
|
|
6913
6913
|
.mcp-name{font-size:15px;font-weight:680;letter-spacing:-.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
6914
6914
|
.mcp-badge{font-size:10px;font-weight:700;letter-spacing:.07em;text-transform:uppercase;color:var(--mcp-muted);border:1px solid var(--mcp-line);border-radius:999px;padding:3px 7px;white-space:nowrap}
|
|
6915
|
+
.mcp-badge.oauth-on{color:#0f766e;border-color:rgba(15,118,110,.25);background:rgba(15,118,110,.07)}
|
|
6915
6916
|
.mcp-meta{display:flex;gap:10px;flex-wrap:wrap;color:var(--mcp-muted);font-size:12px;line-height:1.45}
|
|
6916
6917
|
.mcp-meta code{font:inherit;color:var(--mcp-text);background:var(--mcp-soft);border-radius:5px;padding:1px 5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
6917
6918
|
.mcp-error{color:#9f1239;background:rgba(159,18,57,.06);border:1px solid rgba(159,18,57,.16);border-radius:9px;padding:8px 10px;font-size:12px;line-height:1.4;word-break:break-word}
|
|
@@ -6989,7 +6990,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
6989
6990
|
);
|
|
6990
6991
|
}
|
|
6991
6992
|
|
|
6992
|
-
function ServerCard({ server, busy, onToggle, onTest, onTools, onPrompts, onRemove, tools }) {
|
|
6993
|
+
function ServerCard({ server, busy, onToggle, onTest, onTools, onPrompts, onOAuth, onRemove, tools }) {
|
|
6993
6994
|
const [open, setOpen] = useState(false);
|
|
6994
6995
|
const connected = server.connected;
|
|
6995
6996
|
const status = connected ? "on" : (server.error ? "err" : "off");
|
|
@@ -7005,6 +7006,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7005
7006
|
h("div", { className: "mcp-meta" },
|
|
7006
7007
|
h("span", null, connected ? `подключён · ${server.tools} tools` : server.error ? "ошибка" : "не запущен"),
|
|
7007
7008
|
server.url ? h("code", { title: server.url }, server.url) : h("code", { title: server.command }, server.command || "—"),
|
|
7009
|
+
server.transport === "http" ? h("span", { className: `mcp-badge${server.oauth?.hasToken ? " oauth-on" : ""}` }, server.oauth?.hasToken ? "OAuth ✓" : "OAuth") : null,
|
|
7008
7010
|
),
|
|
7009
7011
|
server.error ? h("div", { className: "mcp-error" }, server.error) : null,
|
|
7010
7012
|
h("div", { className: "mcp-controls" },
|
|
@@ -7012,6 +7014,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7012
7014
|
h(Toggle, { checked: server.trusted, label: "Доверен", disabled: busy, onChange: (value) => onToggle(server.id, { trusted: value }) }),
|
|
7013
7015
|
h("div", { className: "mcp-actions" },
|
|
7014
7016
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onTest(server.id) }, "Проверить"),
|
|
7017
|
+
server.transport === "http" ? h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onOAuth(server.id) }, server.oauth?.hasToken ? "OAuth" : "Войти") : null,
|
|
7015
7018
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onPrompts(server.id) }, "Prompts"),
|
|
7016
7019
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => { setOpen(!open); if (!open) onTools(server.id); } }, open ? "Скрыть" : "Tools"),
|
|
7017
7020
|
h("button", { className: "mcp-btn danger ghost", disabled: busy, onClick: () => onRemove(server.id) }, "Удалить"),
|
|
@@ -7253,6 +7256,44 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7253
7256
|
}
|
|
7254
7257
|
};
|
|
7255
7258
|
|
|
7259
|
+
const startOAuthFlow = async (id) => {
|
|
7260
|
+
const popup = window.open("", "_blank", "popup,width=720,height=780");
|
|
7261
|
+
setBusy(true);
|
|
7262
|
+
setError(null);
|
|
7263
|
+
try {
|
|
7264
|
+
const result = await call(window.__DSH_MCP_CTX__, "oauth-start", { id });
|
|
7265
|
+
if (popup) popup.location.href = result.authorizeUrl;
|
|
7266
|
+
else window.open(result.authorizeUrl, "_blank", "noopener,noreferrer");
|
|
7267
|
+
setToast("Браузер открыт — подтвердите доступ и вернитесь в DSH");
|
|
7268
|
+
const started = Date.now();
|
|
7269
|
+
const timer = setInterval(async () => {
|
|
7270
|
+
try {
|
|
7271
|
+
const status = await call(window.__DSH_MCP_CTX__, "oauth-status", { id });
|
|
7272
|
+
if (status.hasToken) {
|
|
7273
|
+
clearInterval(timer);
|
|
7274
|
+
setToast("OAuth подключён");
|
|
7275
|
+
setTimeout(() => setToast(""), 3000);
|
|
7276
|
+
await load();
|
|
7277
|
+
} else if (status.error) {
|
|
7278
|
+
clearInterval(timer);
|
|
7279
|
+
setError(status.error);
|
|
7280
|
+
} else if (Date.now() - started > 300_000) {
|
|
7281
|
+
clearInterval(timer);
|
|
7282
|
+
setError("OAuth не завершён за 5 минут");
|
|
7283
|
+
}
|
|
7284
|
+
} catch (cause) {
|
|
7285
|
+
clearInterval(timer);
|
|
7286
|
+
setError(cause instanceof Error ? cause.message : String(cause));
|
|
7287
|
+
}
|
|
7288
|
+
}, 2000);
|
|
7289
|
+
} catch (cause) {
|
|
7290
|
+
try { popup?.close(); } catch { /* ignore */ }
|
|
7291
|
+
setError(cause instanceof Error ? cause.message : String(cause));
|
|
7292
|
+
} finally {
|
|
7293
|
+
setBusy(false);
|
|
7294
|
+
}
|
|
7295
|
+
};
|
|
7296
|
+
|
|
7256
7297
|
const presets = PRESETS;
|
|
7257
7298
|
const openPreset = (preset) => setForm({
|
|
7258
7299
|
edit: false,
|
|
@@ -7325,6 +7366,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7325
7366
|
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
7326
7367
|
},
|
|
7327
7368
|
onPrompts: openPrompts,
|
|
7369
|
+
onOAuth: startOAuthFlow,
|
|
7328
7370
|
onRemove: (id) => {
|
|
7329
7371
|
if (window.confirm(`Удалить MCP-сервер «${id}»?`)) void run("remove", { id }, "Сервер удалён");
|
|
7330
7372
|
},
|
|
@@ -7828,7 +7870,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7828
7870
|
if (__kitErrors.length <= 5) console.error("[dsh-desktop-kit] registration failed:", label, message);
|
|
7829
7871
|
};
|
|
7830
7872
|
try {
|
|
7831
|
-
window.__DSH_DESKTOP_KIT__ = { version: "2.
|
|
7873
|
+
window.__DSH_DESKTOP_KIT__ = { version: "2.9.0", parts: __partNames, errors: __kitErrors, ready: false };
|
|
7832
7874
|
} catch {}
|
|
7833
7875
|
const __inject = [];
|
|
7834
7876
|
for (const __part of __parts) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# DSH Desktop Kit 2.8.0 — тест
|
|
2
|
+
|
|
3
|
+
Дата: 2026-11-12.
|
|
4
|
+
|
|
5
|
+
## MCP OAuth 2.1
|
|
6
|
+
|
|
7
|
+
- Protected Resource Metadata: `/.well-known/oauth-protected-resource`.
|
|
8
|
+
- Authorization Server Metadata: RFC 8414 / OIDC.
|
|
9
|
+
- Dynamic Client Registration (RFC 7591).
|
|
10
|
+
- Authorization Code + PKCE S256, state, loopback `127.0.0.1`.
|
|
11
|
+
- `resource` parameter (RFC 8707), audience binding при каждом запросе.
|
|
12
|
+
- Token endpoint: `none`, `client_secret_post`, `client_secret_basic`.
|
|
13
|
+
- Refresh за 60 секунд до истечения; refresh rotation.
|
|
14
|
+
- `mcp.oauth.json` 0600; logout.
|
|
15
|
+
|
|
16
|
+
## Тест
|
|
17
|
+
|
|
18
|
+
- `tools/mcp-oauth-tests.mjs`: fake AS + PRM + DCR + authorize + token + refresh.
|
|
19
|
+
- Проверено: код обменивается, `resource` сохраняется, refresh обновляет токен.
|
|
20
|
+
- `npm test` — exit 0; `build:client` / `check:client` — OK.
|
|
21
|
+
|
|
22
|
+
## Ограничения
|
|
23
|
+
|
|
24
|
+
- Серверы без dynamic registration и без статического client_id пока не подключаются.
|
|
25
|
+
- Sampling ещё не реализован.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# DSH Desktop Kit 2.9.0 — тест
|
|
2
|
+
|
|
3
|
+
Дата: 2026-11-12.
|
|
4
|
+
|
|
5
|
+
## Project instructions
|
|
6
|
+
|
|
7
|
+
- `AGENTS.md` / `CLAUDE.md` в root, вложенных папках до cwd и `.dsh/`.
|
|
8
|
+
- `@path` imports: внутри проекта, глубина ≤ 5, ≤ 20 файлов, ≤ 32 КБ.
|
|
9
|
+
- Symlink за пределы проекта игнорируется с пометкой.
|
|
10
|
+
- Рендер в `<project-instructions>` с source-атрибутом.
|
|
11
|
+
|
|
12
|
+
## MCP roots
|
|
13
|
+
|
|
14
|
+
- Клиент объявляет `roots` capability для stdio.
|
|
15
|
+
- `roots/list` → корень проекта (file URL + basename).
|
|
16
|
+
- `ping` → `{}`.
|
|
17
|
+
- `sampling/createMessage` и `elicitation/create` → `-32601` с понятным текстом.
|
|
18
|
+
|
|
19
|
+
## Проверки
|
|
20
|
+
|
|
21
|
+
- `tools/instructions-tests.mjs` — OK.
|
|
22
|
+
- `tools/mcp-manager-tests.mjs` — OK, включая roots request.
|
|
23
|
+
- `npm test` — exit 0.
|
|
24
|
+
- `build:client` / `check:client` — OK.
|
|
25
|
+
|
|
26
|
+
## Не входит
|
|
27
|
+
|
|
28
|
+
Sampling, elicitation UI, agent teams, marketplace, IDE bridge, OS sandbox.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-desktop-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "DeepSeek Harness desktop kit 2.7: 16 plugins and 30 skills — self-applying skills, token lab, Skills Studio, project memory, GitHub and USB memory transfer, guardrails, repo map, checkpoints, plan mode, browser QA, GitHub review, Claude Code-like hooks/agents/commands, Russian UI, peak guard, chat move and profile transfer.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek-harness",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"build:client": "node tools/build-client.mjs",
|
|
75
75
|
"build:skills": "node tools/build-skill-manifest.mjs",
|
|
76
76
|
"check:client": "node tools/check-client.mjs client.js",
|
|
77
|
-
"test": "node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/browser-qa-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/worktrees-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs",
|
|
77
|
+
"test": "node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/browser-qa-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/instructions-tests.mjs && node tools/mcp-oauth-tests.mjs && node tools/worktrees-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs",
|
|
78
78
|
"skills:cost": "node tools/skill-cost.mjs",
|
|
79
79
|
"skills:check": "node tools/skill-cost.mjs --check",
|
|
80
80
|
"release": "node tools/release.mjs"
|
|
@@ -17,6 +17,7 @@ import { createWorktree, removeWorktree, worktreeSummary } from "./lib/worktrees
|
|
|
17
17
|
import { registerChildPolicyHook } from "./lib/policy.js";
|
|
18
18
|
import { registerCommands } from "./lib/commands.js";
|
|
19
19
|
import { registerAgentApi } from "./lib/api.js";
|
|
20
|
+
import { renderProjectInstructions } from "./lib/instructions.js";
|
|
20
21
|
import { ensureGlobalScaffold, ensureProjectScaffold } from "./lib/scaffold.js";
|
|
21
22
|
import { findDshDir, loadAgents, projectFor } from "./lib/project.js";
|
|
22
23
|
|
|
@@ -219,6 +220,24 @@ export function apply(ctx) {
|
|
|
219
220
|
ctx.logger?.warn?.(`[agent-extensions] system prompt registration failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
220
221
|
}
|
|
221
222
|
|
|
223
|
+
try {
|
|
224
|
+
ctx.systemPrompt.context({
|
|
225
|
+
name: "dsh-agent-extensions: project instructions",
|
|
226
|
+
order: 135,
|
|
227
|
+
interpolate: false,
|
|
228
|
+
required: false,
|
|
229
|
+
text: (assemblyContext) => {
|
|
230
|
+
try {
|
|
231
|
+
return renderProjectInstructions(assemblyContext?.agent?.session?.header?.cwd);
|
|
232
|
+
} catch {
|
|
233
|
+
return "";
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
} catch (error) {
|
|
238
|
+
ctx.logger?.warn?.(`[agent-extensions] instruction prompt skipped: ${error instanceof Error ? error.message : String(error)}`);
|
|
239
|
+
}
|
|
240
|
+
|
|
222
241
|
try {
|
|
223
242
|
ctx.inject(["commands"], (child) => registerCommands(child));
|
|
224
243
|
} catch (error) {
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code-style project instructions.
|
|
3
|
+
*
|
|
4
|
+
* Order (lowest → highest priority):
|
|
5
|
+
* <root>/AGENTS.md, <root>/CLAUDE.md,
|
|
6
|
+
* <root>/.dsh/AGENTS.md,
|
|
7
|
+
* nested AGENTS.md/CLAUDE.md from root to session cwd.
|
|
8
|
+
*
|
|
9
|
+
* `@path` lines import another file. Imports stay inside the project root,
|
|
10
|
+
* are depth-limited and total-size limited.
|
|
11
|
+
*/
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { projectFor } from "./project.js";
|
|
15
|
+
|
|
16
|
+
const MAX_DEPTH = 5;
|
|
17
|
+
const MAX_BYTES = 32_000;
|
|
18
|
+
const MAX_FILES = 20;
|
|
19
|
+
const IMPORT = /^\s*@([^\s#]+)\s*$/u;
|
|
20
|
+
|
|
21
|
+
function inside(root, file) {
|
|
22
|
+
const relative = path.relative(root, path.resolve(file));
|
|
23
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readBounded(file, remaining) {
|
|
27
|
+
const stat = fs.statSync(file);
|
|
28
|
+
if (!stat.isFile()) return "";
|
|
29
|
+
if (stat.size > remaining) throw new Error(`instructions: file too large: ${file}`);
|
|
30
|
+
return fs.readFileSync(file, "utf8");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function expand(file, root, state, depth = 0, realRoot = root) {
|
|
34
|
+
if (depth > MAX_DEPTH) return `[import depth limit: ${file}]`;
|
|
35
|
+
if (state.files.size >= MAX_FILES) return `[import file limit reached: ${file}]`;
|
|
36
|
+
const resolved = path.resolve(file);
|
|
37
|
+
if (!inside(root, resolved)) return `[import outside project ignored: ${file}]`;
|
|
38
|
+
let real;
|
|
39
|
+
try {
|
|
40
|
+
real = fs.realpathSync(resolved);
|
|
41
|
+
} catch {
|
|
42
|
+
return `[unreadable import: ${path.relative(root, resolved)}]`;
|
|
43
|
+
}
|
|
44
|
+
if (!inside(realRoot, real)) return `[import symlink outside project ignored: ${file}]`;
|
|
45
|
+
if (state.files.has(real)) return `[already imported: ${path.relative(root, real)}]`;
|
|
46
|
+
state.files.add(real);
|
|
47
|
+
let text;
|
|
48
|
+
try {
|
|
49
|
+
text = readBounded(real, MAX_BYTES - state.bytes);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return `[unreadable import: ${path.relative(root, real)} — ${error instanceof Error ? error.message : String(error)}]`;
|
|
52
|
+
}
|
|
53
|
+
state.bytes += Buffer.byteLength(text, "utf8");
|
|
54
|
+
return text.split(/\r?\n/u).map((line) => {
|
|
55
|
+
const match = IMPORT.exec(line);
|
|
56
|
+
if (!match) return line;
|
|
57
|
+
const next = path.resolve(path.dirname(real), match[1]);
|
|
58
|
+
if (!inside(root, next)) return `[import outside project ignored: ${match[1]}]`;
|
|
59
|
+
return expand(next, root, state, depth + 1, realRoot);
|
|
60
|
+
}).join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function loadProjectInstructions(cwd) {
|
|
64
|
+
const project = projectFor(cwd);
|
|
65
|
+
const root = project.root;
|
|
66
|
+
const candidates = [];
|
|
67
|
+
const seen = new Set();
|
|
68
|
+
const add = (file, scope) => {
|
|
69
|
+
const resolved = path.resolve(file);
|
|
70
|
+
if (seen.has(resolved) || !fs.existsSync(resolved)) return;
|
|
71
|
+
seen.add(resolved);
|
|
72
|
+
candidates.push({ file: resolved, scope });
|
|
73
|
+
};
|
|
74
|
+
const dirs = [];
|
|
75
|
+
let current = path.resolve(cwd || root);
|
|
76
|
+
while (inside(root, current)) {
|
|
77
|
+
dirs.unshift(current);
|
|
78
|
+
if (current === path.resolve(root)) break;
|
|
79
|
+
const parent = path.dirname(current);
|
|
80
|
+
if (parent === current) break;
|
|
81
|
+
current = parent;
|
|
82
|
+
}
|
|
83
|
+
for (const dir of dirs) {
|
|
84
|
+
for (const name of ["AGENTS.md", "CLAUDE.md"]) add(path.join(dir, name), dir === path.resolve(root) ? "project" : "nested");
|
|
85
|
+
}
|
|
86
|
+
for (const name of ["AGENTS.md", "CLAUDE.md"]) {
|
|
87
|
+
add(path.join(project.dsh ?? path.join(root, ".dsh"), name), "dsh");
|
|
88
|
+
}
|
|
89
|
+
const state = { files: new Set(), bytes: 0 };
|
|
90
|
+
const sections = [];
|
|
91
|
+
const realRoot = (() => { try { return fs.realpathSync(root); } catch { return root; } })();
|
|
92
|
+
for (const item of candidates) {
|
|
93
|
+
const text = expand(item.file, root, state, 0, realRoot);
|
|
94
|
+
if (text.trim().length > 0) sections.push({ ...item, text: text.trim() });
|
|
95
|
+
}
|
|
96
|
+
return { root, sections };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function renderProjectInstructions(cwd) {
|
|
100
|
+
const result = loadProjectInstructions(cwd);
|
|
101
|
+
if (result.sections.length === 0) return "";
|
|
102
|
+
const body = result.sections.map((section) => `<instructions source="${section.scope}:${path.relative(result.root, section.file).split(path.sep).join("/")}">\n${section.text}\n</instructions>`).join("\n");
|
|
103
|
+
return `<project-instructions>\n${body}\n</project-instructions>`;
|
|
104
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-mcp-manager
|
|
2
2
|
|
|
3
|
-
MCP-серверы для DSH без SDK-зависимости: stdio и streamable HTTP, tools, resources, prompts, trust-гейт и премиальный экран в Settings.
|
|
3
|
+
MCP-серверы для DSH без SDK-зависимости: stdio и streamable HTTP, tools, resources, prompts, **OAuth 2.1**, trust-гейт и премиальный экран в Settings.
|
|
4
4
|
|
|
5
5
|

|
|
6
6
|
|
|
@@ -13,6 +13,7 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
13
13
|
- «Проверить» — переподключение и health;
|
|
14
14
|
- «Tools» — список инструментов с описаниями;
|
|
15
15
|
- «Prompts» — промпты сервера: аргументы, запуск и копирование результата;
|
|
16
|
+
- **«Войти» / «OAuth»** у HTTP-сервера — authorization code + PKCE в браузере; токен хранится в `~/.dsh/mcp.oauth.json` (0600) и не попадает в `mcp.json`;
|
|
16
17
|
- «Добавить сервер» — пресеты GitHub / PostgreSQL / Filesystem или ручная форма;
|
|
17
18
|
- токен сохраняется в `~/.dsh/mcp.secrets.json` (0600), а в `mcp.json` остаётся только `${secret:…}`;
|
|
18
19
|
- новые tools появляются в **новом чате** после подключения.
|
|
@@ -21,7 +22,20 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
21
22
|
|
|
22
23
|
<p><img src="screenshots/settings-390.png" alt="MCP Settings на 390px" width="390"> <img src="screenshots/modal-390.png" alt="Форма добавления MCP-сервера" width="390"></p>
|
|
23
24
|
|
|
24
|
-
###
|
|
25
|
+
### OAuth 2.1 для HTTP
|
|
26
|
+
|
|
27
|
+
Кнопка **Войти** запускает полный публичный client flow:
|
|
28
|
+
|
|
29
|
+
1. `/.well-known/oauth-protected-resource` (RFC 9728) — resource и issuer;
|
|
30
|
+
2. metadata authorization server (RFC 8414/OIDC);
|
|
31
|
+
3. dynamic client registration (RFC 7591), если сервер его поддерживает;
|
|
32
|
+
4. authorization code + **PKCE S256**, `state`, loopback `127.0.0.1:<random>/callback`;
|
|
33
|
+
5. обмен кода, `resource` parameter (RFC 8707), audience binding;
|
|
34
|
+
6. refresh при истечении, logout удаляет токен.
|
|
35
|
+
|
|
36
|
+
Токены лежат отдельно от конфига и не логируются. HTTP без TLS разрешён только для localhost. Если сервер не отдаёт metadata или не поддерживает dynamic registration, OAuth завершится понятной ошибкой — токен вручную не подставляется.
|
|
37
|
+
|
|
38
|
+
## Prompts
|
|
25
39
|
|
|
26
40
|
Промпт — это готовый запрос с аргументами, который отдаёт сам MCP-сервер. Нажмите **Prompts**, заполните поля и получите текст. Результат можно скопировать одной кнопкой.
|
|
27
41
|
|
|
@@ -82,7 +96,7 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
82
96
|
|
|
83
97
|
## Ограничения
|
|
84
98
|
|
|
85
|
-
- Нет OAuth: только env/headers. Токены кладите в переменные окружения.
|
|
86
99
|
- Нет sampling: сервер не может запросить генерацию у модели.
|
|
100
|
+
- OAuth поддерживает dynamic registration; серверы только со статическим client_id пока не подключаются автоматически.
|
|
87
101
|
- HTTP-транспорт поддерживает JSON и простой SSE-ответ; интерактивный SSE-стрим с серверными запросами не реализован.
|
|
88
102
|
- MCP-сервер — произвольный процесс. Доверяйте только своим конфигам.
|
|
@@ -47,6 +47,7 @@ window.__ModuleLoader__.load({
|
|
|
47
47
|
.mcp-dot.err{background:#dc2626;box-shadow:0 0 0 3px rgba(220,38,38,.12)}
|
|
48
48
|
.mcp-name{font-size:15px;font-weight:680;letter-spacing:-.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
49
49
|
.mcp-badge{font-size:10px;font-weight:700;letter-spacing:.07em;text-transform:uppercase;color:var(--mcp-muted);border:1px solid var(--mcp-line);border-radius:999px;padding:3px 7px;white-space:nowrap}
|
|
50
|
+
.mcp-badge.oauth-on{color:#0f766e;border-color:rgba(15,118,110,.25);background:rgba(15,118,110,.07)}
|
|
50
51
|
.mcp-meta{display:flex;gap:10px;flex-wrap:wrap;color:var(--mcp-muted);font-size:12px;line-height:1.45}
|
|
51
52
|
.mcp-meta code{font:inherit;color:var(--mcp-text);background:var(--mcp-soft);border-radius:5px;padding:1px 5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
52
53
|
.mcp-error{color:#9f1239;background:rgba(159,18,57,.06);border:1px solid rgba(159,18,57,.16);border-radius:9px;padding:8px 10px;font-size:12px;line-height:1.4;word-break:break-word}
|
|
@@ -124,7 +125,7 @@ window.__ModuleLoader__.load({
|
|
|
124
125
|
);
|
|
125
126
|
}
|
|
126
127
|
|
|
127
|
-
function ServerCard({ server, busy, onToggle, onTest, onTools, onPrompts, onRemove, tools }) {
|
|
128
|
+
function ServerCard({ server, busy, onToggle, onTest, onTools, onPrompts, onOAuth, onRemove, tools }) {
|
|
128
129
|
const [open, setOpen] = useState(false);
|
|
129
130
|
const connected = server.connected;
|
|
130
131
|
const status = connected ? "on" : (server.error ? "err" : "off");
|
|
@@ -140,6 +141,7 @@ window.__ModuleLoader__.load({
|
|
|
140
141
|
h("div", { className: "mcp-meta" },
|
|
141
142
|
h("span", null, connected ? `подключён · ${server.tools} tools` : server.error ? "ошибка" : "не запущен"),
|
|
142
143
|
server.url ? h("code", { title: server.url }, server.url) : h("code", { title: server.command }, server.command || "—"),
|
|
144
|
+
server.transport === "http" ? h("span", { className: `mcp-badge${server.oauth?.hasToken ? " oauth-on" : ""}` }, server.oauth?.hasToken ? "OAuth ✓" : "OAuth") : null,
|
|
143
145
|
),
|
|
144
146
|
server.error ? h("div", { className: "mcp-error" }, server.error) : null,
|
|
145
147
|
h("div", { className: "mcp-controls" },
|
|
@@ -147,6 +149,7 @@ window.__ModuleLoader__.load({
|
|
|
147
149
|
h(Toggle, { checked: server.trusted, label: "Доверен", disabled: busy, onChange: (value) => onToggle(server.id, { trusted: value }) }),
|
|
148
150
|
h("div", { className: "mcp-actions" },
|
|
149
151
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onTest(server.id) }, "Проверить"),
|
|
152
|
+
server.transport === "http" ? h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onOAuth(server.id) }, server.oauth?.hasToken ? "OAuth" : "Войти") : null,
|
|
150
153
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => onPrompts(server.id) }, "Prompts"),
|
|
151
154
|
h("button", { className: "mcp-btn ghost", disabled: busy, onClick: () => { setOpen(!open); if (!open) onTools(server.id); } }, open ? "Скрыть" : "Tools"),
|
|
152
155
|
h("button", { className: "mcp-btn danger ghost", disabled: busy, onClick: () => onRemove(server.id) }, "Удалить"),
|
|
@@ -388,6 +391,44 @@ window.__ModuleLoader__.load({
|
|
|
388
391
|
}
|
|
389
392
|
};
|
|
390
393
|
|
|
394
|
+
const startOAuthFlow = async (id) => {
|
|
395
|
+
const popup = window.open("", "_blank", "popup,width=720,height=780");
|
|
396
|
+
setBusy(true);
|
|
397
|
+
setError(null);
|
|
398
|
+
try {
|
|
399
|
+
const result = await call(window.__DSH_MCP_CTX__, "oauth-start", { id });
|
|
400
|
+
if (popup) popup.location.href = result.authorizeUrl;
|
|
401
|
+
else window.open(result.authorizeUrl, "_blank", "noopener,noreferrer");
|
|
402
|
+
setToast("Браузер открыт — подтвердите доступ и вернитесь в DSH");
|
|
403
|
+
const started = Date.now();
|
|
404
|
+
const timer = setInterval(async () => {
|
|
405
|
+
try {
|
|
406
|
+
const status = await call(window.__DSH_MCP_CTX__, "oauth-status", { id });
|
|
407
|
+
if (status.hasToken) {
|
|
408
|
+
clearInterval(timer);
|
|
409
|
+
setToast("OAuth подключён");
|
|
410
|
+
setTimeout(() => setToast(""), 3000);
|
|
411
|
+
await load();
|
|
412
|
+
} else if (status.error) {
|
|
413
|
+
clearInterval(timer);
|
|
414
|
+
setError(status.error);
|
|
415
|
+
} else if (Date.now() - started > 300_000) {
|
|
416
|
+
clearInterval(timer);
|
|
417
|
+
setError("OAuth не завершён за 5 минут");
|
|
418
|
+
}
|
|
419
|
+
} catch (cause) {
|
|
420
|
+
clearInterval(timer);
|
|
421
|
+
setError(cause instanceof Error ? cause.message : String(cause));
|
|
422
|
+
}
|
|
423
|
+
}, 2000);
|
|
424
|
+
} catch (cause) {
|
|
425
|
+
try { popup?.close(); } catch { /* ignore */ }
|
|
426
|
+
setError(cause instanceof Error ? cause.message : String(cause));
|
|
427
|
+
} finally {
|
|
428
|
+
setBusy(false);
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
|
|
391
432
|
const presets = PRESETS;
|
|
392
433
|
const openPreset = (preset) => setForm({
|
|
393
434
|
edit: false,
|
|
@@ -460,6 +501,7 @@ window.__ModuleLoader__.load({
|
|
|
460
501
|
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
461
502
|
},
|
|
462
503
|
onPrompts: openPrompts,
|
|
504
|
+
onOAuth: startOAuthFlow,
|
|
463
505
|
onRemove: (id) => {
|
|
464
506
|
if (window.confirm(`Удалить MCP-сервер «${id}»?`)) void run("remove", { id }, "Сервер удалён");
|
|
465
507
|
},
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
setGlobalServerFlags,
|
|
13
13
|
upsertGlobalServer,
|
|
14
14
|
} from "./config.js";
|
|
15
|
+
import { logoutOAuth, oauthStatus, startOAuth, storeOAuth } from "./oauth.js";
|
|
15
16
|
|
|
16
17
|
export const RPC_NAMESPACE = "dsh-mcp-manager";
|
|
17
18
|
const ROUTE_BASE = "/api/dsh-mcp-manager";
|
|
@@ -53,7 +54,6 @@ function publicServer(server) { return {
|
|
|
53
54
|
trusted: server.trusted,
|
|
54
55
|
};
|
|
55
56
|
}
|
|
56
|
-
|
|
57
57
|
function presets() {
|
|
58
58
|
return [
|
|
59
59
|
{
|
|
@@ -108,6 +108,7 @@ function configSnapshot(manager) {
|
|
|
108
108
|
error: row?.error ?? "",
|
|
109
109
|
serverInfo: row?.serverInfo ?? null,
|
|
110
110
|
projectTrusted: server.scope !== "project" || Boolean(server.trusted),
|
|
111
|
+
oauth: oauthStatus(server.id),
|
|
111
112
|
};
|
|
112
113
|
}),
|
|
113
114
|
};
|
|
@@ -159,6 +160,39 @@ export function registerApi(ctx, manager) {
|
|
|
159
160
|
};
|
|
160
161
|
|
|
161
162
|
operation("status", async () => configSnapshot(manager));
|
|
163
|
+
const oauthFlows = new Map();
|
|
164
|
+
operation("oauth-start", async (payload) => {
|
|
165
|
+
const config = loadConfig({ cwd: process.cwd() });
|
|
166
|
+
const server = config.servers.find((item) => item.id === String(payload.id ?? ""));
|
|
167
|
+
if (!server) throw new Error("server not found");
|
|
168
|
+
if (!server.url) throw new Error("OAuth is available only for HTTP servers");
|
|
169
|
+
if (!server.trusted) throw new Error(`MCP ${server.id}: trusted=false; включите доверие`);
|
|
170
|
+
if (oauthFlows.has(server.id)) throw new Error("OAuth уже запущен для этого сервера");
|
|
171
|
+
const flow = await startOAuth(server);
|
|
172
|
+
oauthFlows.set(server.id, { state: flow.state, error: "" });
|
|
173
|
+
flow.completion.then(async (token) => {
|
|
174
|
+
storeOAuth(server.id, token);
|
|
175
|
+
oauthFlows.set(server.id, { state: flow.state, error: "" });
|
|
176
|
+
try { await restartGlobal(manager); } catch { /* server can be retried */ }
|
|
177
|
+
}).catch((error) => {
|
|
178
|
+
oauthFlows.set(server.id, { state: flow.state, error: error instanceof Error ? error.message : String(error) });
|
|
179
|
+
}).finally(() => {
|
|
180
|
+
setTimeout(() => oauthFlows.delete(server.id), 60_000).unref?.();
|
|
181
|
+
});
|
|
182
|
+
return { authorizeUrl: flow.authorizeUrl, state: flow.state, redirectUri: flow.redirectUri };
|
|
183
|
+
});
|
|
184
|
+
operation("oauth-status", async (payload) => {
|
|
185
|
+
const id = String(payload.id ?? "");
|
|
186
|
+
const pending = oauthFlows.get(id);
|
|
187
|
+
return { ...oauthStatus(id), pending: Boolean(pending), error: pending?.error ?? "" };
|
|
188
|
+
});
|
|
189
|
+
operation("oauth-logout", async (payload) => {
|
|
190
|
+
const id = String(payload.id ?? "");
|
|
191
|
+
logoutOAuth(id);
|
|
192
|
+
oauthFlows.delete(id);
|
|
193
|
+
await restartGlobal(manager);
|
|
194
|
+
return { ...oauthStatus(id), pending: false, error: "" };
|
|
195
|
+
});
|
|
162
196
|
operation("presets", async () => ({ presets: presets() }));
|
|
163
197
|
operation("trust-project", async () => {
|
|
164
198
|
const config = loadConfig({ cwd: process.cwd() });
|
|
@@ -29,6 +29,11 @@ class StdioTransport {
|
|
|
29
29
|
this.child = null;
|
|
30
30
|
this.closed = false;
|
|
31
31
|
this.stderr = "";
|
|
32
|
+
this.requestHandler = null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
setRequestHandler(handler) {
|
|
36
|
+
this.requestHandler = handler;
|
|
32
37
|
}
|
|
33
38
|
|
|
34
39
|
async start() {
|
|
@@ -42,6 +47,18 @@ class StdioTransport {
|
|
|
42
47
|
reader.on("line", (line) => {
|
|
43
48
|
const message = parseJsonRpc(line);
|
|
44
49
|
if (!message) return;
|
|
50
|
+
if (message.method !== undefined && message.id !== undefined) {
|
|
51
|
+
const handler = this.requestHandler;
|
|
52
|
+
Promise.resolve()
|
|
53
|
+
.then(() => handler ? handler(message) : Promise.reject(Object.assign(new Error("method not supported"), { code: -32601 })))
|
|
54
|
+
.then((result) => {
|
|
55
|
+
this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, result: result ?? {} })}\n`);
|
|
56
|
+
})
|
|
57
|
+
.catch((error) => {
|
|
58
|
+
this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: error?.code ?? -32603, message: error instanceof Error ? error.message : String(error) } })}\n`);
|
|
59
|
+
});
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
45
62
|
if (message.id !== undefined && this.pending.has(String(message.id))) {
|
|
46
63
|
const waiter = this.pending.get(String(message.id));
|
|
47
64
|
this.pending.delete(String(message.id));
|
|
@@ -110,12 +127,14 @@ class HttpTransport {
|
|
|
110
127
|
const controller = new AbortController();
|
|
111
128
|
const timer = setTimeout(() => controller.abort(new Error("timeout")), timeoutMs);
|
|
112
129
|
try {
|
|
130
|
+
const token = typeof this.config.tokenProvider === "function" ? await this.config.tokenProvider() : "";
|
|
113
131
|
const response = await fetch(this.config.url, {
|
|
114
132
|
method: "POST",
|
|
115
133
|
headers: {
|
|
116
134
|
"content-type": "application/json",
|
|
117
135
|
accept: "application/json, text/event-stream",
|
|
118
136
|
...(this.sessionId ? { "mcp-session-id": this.sessionId } : {}),
|
|
137
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
119
138
|
...this.config.headers,
|
|
120
139
|
},
|
|
121
140
|
body: JSON.stringify({ jsonrpc: "2.0", id: makeId(), method, params: params ?? {} }),
|
|
@@ -170,11 +189,13 @@ export class McpClient {
|
|
|
170
189
|
|
|
171
190
|
async connect() {
|
|
172
191
|
await this.transport.start?.();
|
|
192
|
+
const canHandle = typeof this.transport.setRequestHandler === "function" && typeof this.config.onServerRequest === "function";
|
|
193
|
+
if (canHandle) this.transport.setRequestHandler(this.config.onServerRequest);
|
|
173
194
|
const result = await this.transport.request(
|
|
174
195
|
"initialize",
|
|
175
196
|
{
|
|
176
197
|
protocolVersion: PROTOCOL_VERSION,
|
|
177
|
-
capabilities: {},
|
|
198
|
+
capabilities: canHandle ? { roots: { listChanged: false } } : {},
|
|
178
199
|
clientInfo: { name: "dsh-mcp-manager", version: "1.0.0" },
|
|
179
200
|
},
|
|
180
201
|
this.config.timeoutMs,
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
* MCP server manager: connection lifecycle, tool mapping and status.
|
|
3
3
|
*/
|
|
4
4
|
import { McpClient } from "./client.js";
|
|
5
|
+
import { getAccessToken } from "./oauth.js";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
5
8
|
|
|
6
9
|
function sanitize(value) {
|
|
7
10
|
return String(value ?? "").replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 48);
|
|
@@ -45,7 +48,25 @@ export class McpManager {
|
|
|
45
48
|
if (this.closed) throw new Error("MCP manager is closed");
|
|
46
49
|
const existing = this.clients.get(server.id);
|
|
47
50
|
if (existing?.client?.connected) return existing;
|
|
48
|
-
const
|
|
51
|
+
const root = path.resolve(server.cwd || process.cwd());
|
|
52
|
+
const client = new McpClient({
|
|
53
|
+
...server,
|
|
54
|
+
tokenProvider: server.url ? () => getAccessToken(server.id, { resource: server.url }).catch(() => null) : undefined,
|
|
55
|
+
onServerRequest: (message) => {
|
|
56
|
+
if (message.method === "roots/list") {
|
|
57
|
+
return {
|
|
58
|
+
roots: [{
|
|
59
|
+
uri: pathToFileURL(root).href,
|
|
60
|
+
name: path.basename(root) || "workspace",
|
|
61
|
+
}],
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (message.method === "ping") return {};
|
|
65
|
+
const error = new Error(`${message.method}: not supported by DSH; sampling and elicitation require explicit approval`);
|
|
66
|
+
error.code = -32601;
|
|
67
|
+
throw error;
|
|
68
|
+
},
|
|
69
|
+
}, this.ctx.logger);
|
|
49
70
|
try {
|
|
50
71
|
await client.connect();
|
|
51
72
|
if (this.closed) {
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP OAuth 2.1 for HTTP servers.
|
|
3
|
+
*
|
|
4
|
+
* Public client + authorization code + PKCE S256 + loopback redirect.
|
|
5
|
+
* Discovery: RFC 9728 protected-resource metadata, then RFC 8414/OIDC
|
|
6
|
+
* authorization-server metadata. Registration: RFC 7591 dynamic client
|
|
7
|
+
* registration. Tokens are stored outside mcp.json in `mcp.oauth.json` (0600).
|
|
8
|
+
*/
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import http from "node:http";
|
|
12
|
+
import { mcpHome } from "./config.js";
|
|
13
|
+
|
|
14
|
+
const TIMEOUT_MS = 5 * 60_000;
|
|
15
|
+
const CLIENT_NAME = "DSH Desktop Kit";
|
|
16
|
+
|
|
17
|
+
export function oauthTokenPath(home = mcpHome()) {
|
|
18
|
+
return `${home.replace(/[\\/]+$/u, "")}/mcp.oauth.json`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function loadOAuthTokens(home = mcpHome()) {
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(fs.readFileSync(oauthTokenPath(home), "utf8"));
|
|
24
|
+
return parsed && typeof parsed === "object" && parsed.servers && typeof parsed.servers === "object" ? parsed : { version: 1, servers: {} };
|
|
25
|
+
} catch {
|
|
26
|
+
return { version: 1, servers: {} };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function saveOAuthTokens(data, home = mcpHome()) {
|
|
31
|
+
const file = oauthTokenPath(home);
|
|
32
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
33
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
34
|
+
fs.writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
35
|
+
fs.renameSync(temp, file);
|
|
36
|
+
return file;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function oauthStatus(serverId, home = mcpHome()) {
|
|
40
|
+
const token = loadOAuthTokens(home).servers?.[serverId];
|
|
41
|
+
if (!token) return { hasToken: false, expiresAt: null, scope: "", resource: "" };
|
|
42
|
+
return {
|
|
43
|
+
hasToken: true,
|
|
44
|
+
expiresAt: token.expiresAt ?? null,
|
|
45
|
+
scope: token.scope ?? "",
|
|
46
|
+
resource: token.resource ?? "",
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function logoutOAuth(serverId, home = mcpHome()) {
|
|
51
|
+
const data = loadOAuthTokens(home);
|
|
52
|
+
if (data.servers?.[serverId]) {
|
|
53
|
+
delete data.servers[serverId];
|
|
54
|
+
saveOAuthTokens(data, home);
|
|
55
|
+
}
|
|
56
|
+
return { removed: true };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function base64url(buffer) {
|
|
60
|
+
return buffer.toString("base64").replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/gu, "");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function pkce() {
|
|
64
|
+
const verifier = base64url(crypto.randomBytes(48));
|
|
65
|
+
const challenge = base64url(crypto.createHash("sha256").update(verifier).digest());
|
|
66
|
+
return { verifier, challenge };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function stateValue() {
|
|
70
|
+
return base64url(crypto.randomBytes(24));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function sameState(left, right) {
|
|
74
|
+
const a = Buffer.from(String(left));
|
|
75
|
+
const b = Buffer.from(String(right));
|
|
76
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function json(url, init = {}, fetchImpl = fetch) {
|
|
80
|
+
const response = await fetchImpl(url, {
|
|
81
|
+
...init,
|
|
82
|
+
headers: { accept: "application/json", ...(init.headers ?? {}) },
|
|
83
|
+
signal: init.signal ?? AbortSignal.timeout(15_000),
|
|
84
|
+
});
|
|
85
|
+
const text = await response.text();
|
|
86
|
+
let body;
|
|
87
|
+
try { body = text ? JSON.parse(text) : null; } catch { body = null; }
|
|
88
|
+
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}${text ? ` — ${text.slice(0, 300)}` : ""}`);
|
|
89
|
+
if (!body || typeof body !== "object") throw new Error(`${url}: invalid JSON`);
|
|
90
|
+
return body;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function normalizeResource(serverUrl) {
|
|
94
|
+
const url = new URL(serverUrl);
|
|
95
|
+
if (url.protocol !== "https:" && !["127.0.0.1", "localhost", "::1"].includes(url.hostname)) {
|
|
96
|
+
throw new Error("MCP OAuth requires https (http is allowed only for localhost)");
|
|
97
|
+
}
|
|
98
|
+
url.hash = "";
|
|
99
|
+
return url.href;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function discover(serverUrl, fetchImpl) {
|
|
103
|
+
const resource = normalizeResource(serverUrl);
|
|
104
|
+
const base = new URL(resource);
|
|
105
|
+
const candidates = [
|
|
106
|
+
`${base.origin}/.well-known/oauth-protected-resource${base.pathname}`,
|
|
107
|
+
`${base.origin}/.well-known/oauth-protected-resource`,
|
|
108
|
+
];
|
|
109
|
+
let prm = null;
|
|
110
|
+
for (const candidate of [...new Set(candidates)]) {
|
|
111
|
+
try { prm = await json(candidate, {}, fetchImpl); break; } catch { /* try next */ }
|
|
112
|
+
}
|
|
113
|
+
if (!prm) throw new Error("OAuth: protected resource metadata not found (/.well-known/oauth-protected-resource)");
|
|
114
|
+
const issuer = Array.isArray(prm.authorization_servers) && prm.authorization_servers[0]
|
|
115
|
+
? String(prm.authorization_servers[0])
|
|
116
|
+
: base.origin;
|
|
117
|
+
const issuerUrl = new URL(issuer);
|
|
118
|
+
const metadataUrls = [
|
|
119
|
+
`${issuerUrl.origin}/.well-known/oauth-authorization-server${issuerUrl.pathname}`,
|
|
120
|
+
`${issuerUrl.origin}/.well-known/oauth-authorization-server`,
|
|
121
|
+
`${issuerUrl.origin}/.well-known/openid-configuration${issuerUrl.pathname}`,
|
|
122
|
+
`${issuerUrl.origin}/.well-known/openid-configuration`,
|
|
123
|
+
];
|
|
124
|
+
let metadata = null;
|
|
125
|
+
for (const candidate of [...new Set(metadataUrls)]) {
|
|
126
|
+
try { metadata = await json(candidate, {}, fetchImpl); break; } catch { /* try next */ }
|
|
127
|
+
}
|
|
128
|
+
if (!metadata?.authorization_endpoint || !metadata?.token_endpoint) {
|
|
129
|
+
throw new Error("OAuth: authorization-server metadata is missing authorization_endpoint/token_endpoint");
|
|
130
|
+
}
|
|
131
|
+
if (metadata.issuer && new URL(String(metadata.issuer)).origin !== issuerUrl.origin) {
|
|
132
|
+
throw new Error("OAuth: authorization-server metadata issuer does not match the advertised issuer");
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
resource,
|
|
136
|
+
issuer,
|
|
137
|
+
authorizationEndpoint: String(metadata.authorization_endpoint),
|
|
138
|
+
tokenEndpoint: String(metadata.token_endpoint),
|
|
139
|
+
registrationEndpoint: typeof metadata.registration_endpoint === "string" ? metadata.registration_endpoint : "",
|
|
140
|
+
revocationEndpoint: typeof metadata.revocation_endpoint === "string" ? metadata.revocation_endpoint : "",
|
|
141
|
+
scopes: Array.isArray(prm.scopes_supported) ? prm.scopes_supported.map(String) : [],
|
|
142
|
+
tokenEndpointAuthMethods: Array.isArray(metadata.token_endpoint_auth_methods_supported)
|
|
143
|
+
? metadata.token_endpoint_auth_methods_supported.map(String)
|
|
144
|
+
: ["none"],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function registerClient(meta, redirectUri, fetchImpl) {
|
|
149
|
+
if (!meta.registrationEndpoint) throw new Error("OAuth: server does not expose dynamic client registration; register the client manually");
|
|
150
|
+
const body = await json(meta.registrationEndpoint, {
|
|
151
|
+
method: "POST",
|
|
152
|
+
headers: { "content-type": "application/json" },
|
|
153
|
+
body: JSON.stringify({
|
|
154
|
+
client_name: CLIENT_NAME,
|
|
155
|
+
redirect_uris: [redirectUri],
|
|
156
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
157
|
+
response_types: ["code"],
|
|
158
|
+
token_endpoint_auth_method: meta.tokenEndpointAuthMethods.includes("none") ? "none" : meta.tokenEndpointAuthMethods[0],
|
|
159
|
+
}),
|
|
160
|
+
}, fetchImpl);
|
|
161
|
+
if (!body.client_id) throw new Error("OAuth: registration response has no client_id");
|
|
162
|
+
return {
|
|
163
|
+
clientId: String(body.client_id),
|
|
164
|
+
clientSecret: typeof body.client_secret === "string" ? body.client_secret : "",
|
|
165
|
+
authMethod: typeof body.token_endpoint_auth_method === "string" ? body.token_endpoint_auth_method : "none",
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function authorizationUrl(meta, client, redirectUri, state, challenge) {
|
|
170
|
+
const url = new URL(meta.authorizationEndpoint);
|
|
171
|
+
url.searchParams.set("response_type", "code");
|
|
172
|
+
url.searchParams.set("client_id", client.clientId);
|
|
173
|
+
url.searchParams.set("redirect_uri", redirectUri);
|
|
174
|
+
url.searchParams.set("state", state);
|
|
175
|
+
url.searchParams.set("code_challenge", challenge);
|
|
176
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
177
|
+
url.searchParams.set("resource", meta.resource);
|
|
178
|
+
if (meta.scopes.length > 0) url.searchParams.set("scope", meta.scopes.join(" "));
|
|
179
|
+
return url.href;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function listen(server) {
|
|
183
|
+
return new Promise((resolve, reject) => {
|
|
184
|
+
server.once("error", reject);
|
|
185
|
+
server.listen(0, "127.0.0.1", () => resolve(server.address().port));
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function close(server) {
|
|
190
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function exchangeCode(meta, client, code, verifier, redirectUri, fetchImpl) {
|
|
194
|
+
const body = new URLSearchParams({
|
|
195
|
+
grant_type: "authorization_code",
|
|
196
|
+
code,
|
|
197
|
+
redirect_uri: redirectUri,
|
|
198
|
+
client_id: client.clientId,
|
|
199
|
+
code_verifier: verifier,
|
|
200
|
+
resource: meta.resource,
|
|
201
|
+
});
|
|
202
|
+
if (client.clientSecret && client.authMethod !== "none") body.set("client_secret", client.clientSecret);
|
|
203
|
+
return tokenRequest(meta.tokenEndpoint, body, fetchImpl, client);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function tokenRequest(tokenEndpoint, body, fetchImpl, client = null) {
|
|
207
|
+
const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
|
|
208
|
+
if (client?.clientSecret && client.authMethod === "client_secret_basic") {
|
|
209
|
+
headers.authorization = `Basic ${Buffer.from(`${client.clientId}:${client.clientSecret}`).toString("base64")}`;
|
|
210
|
+
body.delete("client_secret");
|
|
211
|
+
}
|
|
212
|
+
const response = await fetchImpl(tokenEndpoint, {
|
|
213
|
+
method: "POST",
|
|
214
|
+
headers,
|
|
215
|
+
body: body.toString(),
|
|
216
|
+
signal: AbortSignal.timeout(20_000),
|
|
217
|
+
});
|
|
218
|
+
const text = await response.text();
|
|
219
|
+
let parsed = null;
|
|
220
|
+
try { parsed = text ? JSON.parse(text) : null; } catch { parsed = null; }
|
|
221
|
+
if (!response.ok) throw new Error(`OAuth token endpoint: HTTP ${response.status}${text ? ` — ${text.slice(0, 300)}` : ""}`);
|
|
222
|
+
if (!parsed || typeof parsed.access_token !== "string") throw new Error("OAuth token endpoint: no access_token");
|
|
223
|
+
return parsed;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function expiry(seconds) {
|
|
227
|
+
const value = Number(seconds);
|
|
228
|
+
return new Date(Date.now() + (Number.isFinite(value) && value > 0 ? value : 3600) * 1000).toISOString();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Start an OAuth flow. The returned completion resolves after the loopback
|
|
233
|
+
* callback and token exchange; callers should persist it.
|
|
234
|
+
*/
|
|
235
|
+
export async function startOAuth(server, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS } = {}) {
|
|
236
|
+
if (!server?.url) throw new Error("OAuth is available only for HTTP MCP servers");
|
|
237
|
+
const meta = await discover(server.url, fetchImpl);
|
|
238
|
+
const verifier = pkce();
|
|
239
|
+
const state = stateValue();
|
|
240
|
+
let settle;
|
|
241
|
+
const completion = new Promise((resolve, reject) => {
|
|
242
|
+
settle = { resolve, reject };
|
|
243
|
+
});
|
|
244
|
+
let serverHandle;
|
|
245
|
+
let timer;
|
|
246
|
+
const finish = async (fn, value) => {
|
|
247
|
+
if (timer) clearTimeout(timer);
|
|
248
|
+
try { if (serverHandle) await close(serverHandle); } catch { /* best effort */ }
|
|
249
|
+
fn(value);
|
|
250
|
+
};
|
|
251
|
+
const handler = async (req, res) => {
|
|
252
|
+
try {
|
|
253
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
254
|
+
if (url.pathname !== "/callback") {
|
|
255
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
256
|
+
res.end("Not found");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const error = url.searchParams.get("error");
|
|
260
|
+
if (error) {
|
|
261
|
+
res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
262
|
+
res.end("<h1>OAuth отклонён</h1><p>Можно закрыть окно и вернуться в DSH.</p>");
|
|
263
|
+
await finish(settle.reject, new Error(`OAuth: ${error}${url.searchParams.get("error_description") ? ` — ${url.searchParams.get("error_description")}` : ""}`));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (!sameState(url.searchParams.get("state"), state)) {
|
|
267
|
+
res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
268
|
+
res.end("<h1>Неверный state</h1>");
|
|
269
|
+
await finish(settle.reject, new Error("OAuth: state mismatch"));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const code = url.searchParams.get("code");
|
|
273
|
+
if (!code) throw new Error("OAuth: callback has no code");
|
|
274
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
275
|
+
res.end("<h1>DSH подключён</h1><p>Можно закрыть окно и вернуться в DSH.</p>");
|
|
276
|
+
const tokens = await exchangeCode(meta, client, code, verifier.verifier, redirectUri, fetchImpl);
|
|
277
|
+
await finish(settle.resolve, { tokens, meta, client, redirectUri });
|
|
278
|
+
} catch (error) {
|
|
279
|
+
try { res.writeHead(500, { "content-type": "text/plain; charset=utf-8" }); res.end("OAuth failed"); } catch { /* already sent */ }
|
|
280
|
+
await finish(settle.reject, error);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
serverHandle = http.createServer((req, res) => { void handler(req, res); });
|
|
284
|
+
const port = await listen(serverHandle);
|
|
285
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
286
|
+
let client;
|
|
287
|
+
try {
|
|
288
|
+
client = await registerClient(meta, redirectUri, fetchImpl);
|
|
289
|
+
} catch (error) {
|
|
290
|
+
await close(serverHandle);
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
const authorizeUrl = authorizationUrl(meta, client, redirectUri, state, verifier.challenge);
|
|
294
|
+
timer = setTimeout(() => {
|
|
295
|
+
void finish(settle.reject, new Error("OAuth: timed out (5 minutes)"));
|
|
296
|
+
}, timeoutMs);
|
|
297
|
+
timer.unref?.();
|
|
298
|
+
return {
|
|
299
|
+
authorizeUrl,
|
|
300
|
+
state,
|
|
301
|
+
redirectUri,
|
|
302
|
+
completion: completion.then(({ tokens, meta: metadata, client: clientInfo }) => ({
|
|
303
|
+
accessToken: tokens.access_token,
|
|
304
|
+
refreshToken: tokens.refresh_token ?? "",
|
|
305
|
+
tokenType: tokens.token_type ?? "Bearer",
|
|
306
|
+
scope: tokens.scope ?? metadata.scopes.join(" "),
|
|
307
|
+
expiresAt: expiry(tokens.expires_in),
|
|
308
|
+
tokenEndpoint: metadata.tokenEndpoint,
|
|
309
|
+
clientId: clientInfo.clientId,
|
|
310
|
+
clientSecret: clientInfo.clientSecret,
|
|
311
|
+
authMethod: clientInfo.authMethod,
|
|
312
|
+
resource: metadata.resource,
|
|
313
|
+
})),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function storeOAuth(serverId, token, home = mcpHome()) {
|
|
318
|
+
const data = loadOAuthTokens(home);
|
|
319
|
+
data.servers[serverId] = token;
|
|
320
|
+
saveOAuthTokens(data, home);
|
|
321
|
+
return token;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Return a usable access token, refreshing when it expires within 60 seconds.
|
|
326
|
+
* Returns null when the server was never authorized.
|
|
327
|
+
*/
|
|
328
|
+
export async function getAccessToken(serverId, { fetchImpl = fetch, home = mcpHome(), resource = "" } = {}) {
|
|
329
|
+
const data = loadOAuthTokens(home);
|
|
330
|
+
const token = data.servers?.[serverId];
|
|
331
|
+
if (!token?.accessToken) return null;
|
|
332
|
+
if (resource && token.resource) {
|
|
333
|
+
try {
|
|
334
|
+
const requested = new URL(resource);
|
|
335
|
+
requested.hash = "";
|
|
336
|
+
const bound = new URL(token.resource);
|
|
337
|
+
bound.hash = "";
|
|
338
|
+
if (requested.href !== bound.href) throw new Error(`OAuth token audience mismatch for ${serverId}; sign in again`);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (error instanceof Error && error.message.includes("audience mismatch")) throw error;
|
|
341
|
+
throw new Error(`OAuth token has an invalid resource for ${serverId}; sign in again`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const expires = Date.parse(token.expiresAt ?? "");
|
|
345
|
+
if (!Number.isFinite(expires) || expires > Date.now() + 60_000) return token.accessToken;
|
|
346
|
+
if (!token.refreshToken) throw new Error(`OAuth token expired for ${serverId}; sign in again`);
|
|
347
|
+
const body = new URLSearchParams({
|
|
348
|
+
grant_type: "refresh_token",
|
|
349
|
+
refresh_token: token.refreshToken,
|
|
350
|
+
client_id: token.clientId,
|
|
351
|
+
resource: token.resource,
|
|
352
|
+
});
|
|
353
|
+
if (token.clientSecret && token.authMethod !== "none") body.set("client_secret", token.clientSecret);
|
|
354
|
+
const refreshed = await tokenRequest(token.tokenEndpoint, body, fetchImpl, {
|
|
355
|
+
clientId: token.clientId,
|
|
356
|
+
clientSecret: token.clientSecret,
|
|
357
|
+
authMethod: token.authMethod,
|
|
358
|
+
});
|
|
359
|
+
const next = {
|
|
360
|
+
...token,
|
|
361
|
+
accessToken: refreshed.access_token,
|
|
362
|
+
refreshToken: refreshed.refresh_token ?? token.refreshToken,
|
|
363
|
+
expiresAt: expiry(refreshed.expires_in),
|
|
364
|
+
scope: refreshed.scope ?? token.scope,
|
|
365
|
+
};
|
|
366
|
+
storeOAuth(serverId, next, home);
|
|
367
|
+
return next.accessToken;
|
|
368
|
+
}
|
|
Binary file
|