dsh-desktop-kit 2.7.9 → 2.8.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 +16 -0
- package/README.md +18 -18
- package/client.js +44 -2
- package/docs/TEST-2.7.10.md +29 -0
- package/docs/TEST-2.8.0.md +25 -0
- package/doctor.ps1 +26 -6
- package/package.json +2 -2
- package/plugins/dsh-agent-extensions/index.js +4 -1
- package/plugins/dsh-agent-extensions/lib/runs.js +6 -1
- package/plugins/dsh-agent-extensions/lib/worktrees.js +29 -12
- 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 +2 -0
- package/plugins/dsh-mcp-manager/lib/manager.js +5 -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,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.8.0 (2026-11-12)
|
|
4
|
+
|
|
5
|
+
- **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.
|
|
6
|
+
- **Token storage.** `~/.dsh/mcp.oauth.json` (0600), отдельно от `mcp.json`; токены не логируются; HTTPS обязателен вне localhost.
|
|
7
|
+
- **UI.** Кнопка «Войти»/«OAuth» у HTTP-сервера, статус OAuth в карточке, повторный consent; `oauth-start`, `oauth-status`, `oauth-logout`.
|
|
8
|
+
- **HTTP transport.** Автоматический `Authorization: Bearer` из token store с refresh за 60 секунд до истечения.
|
|
9
|
+
- **Тесты.** `mcp-oauth-tests`: discovery, DCR, PKCE, callback, token store, refresh, audience.
|
|
10
|
+
|
|
11
|
+
## 2.7.10 (2026-11-12)
|
|
12
|
+
|
|
13
|
+
- **Worktree hardening.** Managed worktrees всегда привязаны к главному worktree: запуск из вложенного worktree больше не создаёт nested `.dsh/worktrees`. Пути нормализуются, фильтрация идёт через `path.relative`.
|
|
14
|
+
- **Redaction фоновых запусков.** `task` и `result` в `.dsh/agents/runs.json` очищаются от `sk-*`, GitHub-токенов, Bearer и `password/token=...` до записи.
|
|
15
|
+
- **Корректные ошибки background.** Если старт фонового агента не удался, tool возвращает `ok:false`, а не успех с текстом ошибки.
|
|
16
|
+
- **Doctor.** Показывает real directory vs junction, stale `dsh-desktop-kit_tmp_*` (EPERM), отдельно `Dependency` и `Package`.
|
|
17
|
+
- **Тесты.** Worktree edge cases (bad slug/base, duplicate, linked worktree), redaction, cancel race.
|
|
18
|
+
|
|
3
19
|
## 2.7.9 (2026-11-12)
|
|
4
20
|
|
|
5
21
|
- **Worktrees.** `project_worktree` (`list|create|remove`) создаёт `.dsh/worktrees/<slug>` на ветке `dsh/<slug>`, пишет путь в `.git/info/exclude`, отказывает в удалении грязного worktree без `force`.
|
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
|
|
|
@@ -24,11 +24,11 @@
|
|
|
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
26
|
|
|
27
|
-

|
|
28
28
|
|
|
29
|
-

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

|
|
120
120
|
|
|
121
|
-

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

|
|
128
128
|
|
|
129
|
-

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

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

|
|
138
138
|
|
|
139
|
-

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

|
|
150
150
|
|
|
151
|
-

|
|
152
152
|
|
|
153
|
-

|
|
154
154
|
|
|
155
155
|
Подробности и настройки — [plugins/dsh-peak-guard/README.md](plugins/dsh-peak-guard/README.md).
|
|
156
156
|
|
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.8.0", parts: __partNames, errors: __kitErrors, ready: false };
|
|
7832
7874
|
} catch {}
|
|
7833
7875
|
const __inject = [];
|
|
7834
7876
|
for (const __part of __parts) {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# DSH Desktop Kit 2.7.10 — тест
|
|
2
|
+
|
|
3
|
+
Дата: 2026-11-12.
|
|
4
|
+
|
|
5
|
+
## Hardening worktrees
|
|
6
|
+
|
|
7
|
+
- `repoRoot()` берёт главный worktree из `git worktree list --porcelain`; запуск из linked worktree создаёт worktree в главном repo.
|
|
8
|
+
- `gitRoot` и пути нормализуются через `path.resolve`; фильтрация — `path.relative`, без ложных prefix-совпадений.
|
|
9
|
+
- Тесты: bad slug, missing base, duplicate, linked-worktree anchor.
|
|
10
|
+
|
|
11
|
+
## Redaction
|
|
12
|
+
|
|
13
|
+
- `runs.json` не хранит `sk-*`, GitHub-токены, Bearer и `password/token=...`; заменяются на `[redacted]` до clip.
|
|
14
|
+
- Тест: task с секретом не содержит исходного значения.
|
|
15
|
+
|
|
16
|
+
## Background errors
|
|
17
|
+
|
|
18
|
+
- Старт с ошибкой возвращает `ok:false` (tool), запись run получает `failed`.
|
|
19
|
+
|
|
20
|
+
## Doctor
|
|
21
|
+
|
|
22
|
+
- `Dependency` / `Package` разделены.
|
|
23
|
+
- Junction показывается как development link.
|
|
24
|
+
- Stale `dsh-desktop-kit_tmp_*` обнаруживается и увеличивает issue count.
|
|
25
|
+
|
|
26
|
+
## Прогон
|
|
27
|
+
|
|
28
|
+
- `worktrees-tests`, `background-agents-tests`, `agent-extensions-tests`, `npm test` — OK.
|
|
29
|
+
- `build:client` / `check:client` — OK.
|
|
@@ -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 ещё не реализован.
|
package/doctor.ps1
CHANGED
|
@@ -45,9 +45,9 @@ $issues = 0
|
|
|
45
45
|
$dependency = $null
|
|
46
46
|
if ($json.dependencies) { $dependency = $json.dependencies.'dsh-desktop-kit' }
|
|
47
47
|
if ($dependency) {
|
|
48
|
-
Write-Host "
|
|
48
|
+
Write-Host "Dependency: $dependency" -ForegroundColor Green
|
|
49
49
|
} else {
|
|
50
|
-
Write-Host "
|
|
50
|
+
Write-Host "Dependency: not installed" -ForegroundColor Red
|
|
51
51
|
$issues += 1
|
|
52
52
|
}
|
|
53
53
|
|
|
@@ -62,14 +62,34 @@ if ($bundles -contains "dsh-desktop-kit") {
|
|
|
62
62
|
|
|
63
63
|
$link = Join-Path $profileDir "node_modules\dsh-desktop-kit"
|
|
64
64
|
if (Test-Path $link) {
|
|
65
|
-
|
|
65
|
+
$item = Get-Item -Path $link -Force
|
|
66
|
+
if ($item.LinkType -eq "Junction" -or $item.LinkType -eq "SymbolicLink") {
|
|
67
|
+
Write-Host "Package: linked -> $($item.Target)" -ForegroundColor Yellow
|
|
68
|
+
Write-Host " development link; production installs use a real directory"
|
|
69
|
+
} else {
|
|
70
|
+
Write-Host "Package: real directory" -ForegroundColor Green
|
|
71
|
+
}
|
|
66
72
|
$kitPackage = Join-Path $link "package.json"
|
|
67
73
|
if (Test-Path $kitPackage) {
|
|
68
|
-
|
|
69
|
-
|
|
74
|
+
try {
|
|
75
|
+
$kit = Get-Content -Path $kitPackage -Raw | ConvertFrom-Json
|
|
76
|
+
Write-Host "Kit: $($kit.version)" -ForegroundColor Green
|
|
77
|
+
} catch {
|
|
78
|
+
Write-Host "Kit: package.json is unreadable" -ForegroundColor Red
|
|
79
|
+
$issues += 1
|
|
80
|
+
}
|
|
81
|
+
} else {
|
|
82
|
+
Write-Host "Kit: package.json missing" -ForegroundColor Red
|
|
83
|
+
$issues += 1
|
|
84
|
+
}
|
|
85
|
+
$tmp = @(Get-ChildItem -Path (Join-Path $profileDir "node_modules") -Directory -Filter "dsh-desktop-kit_tmp_*" -ErrorAction SilentlyContinue)
|
|
86
|
+
if ($tmp.Count -gt 0) {
|
|
87
|
+
Write-Host "Stale: $($tmp.Count) dsh-desktop-kit_tmp_* folder(s); pnpm may fail with EPERM" -ForegroundColor Yellow
|
|
88
|
+
Write-Host " remove them, then re-run the install"
|
|
89
|
+
$issues += 1
|
|
70
90
|
}
|
|
71
91
|
} else {
|
|
72
|
-
Write-Host "
|
|
92
|
+
Write-Host "Package: missing (run install.ps1 again)" -ForegroundColor Red
|
|
73
93
|
$issues += 1
|
|
74
94
|
}
|
|
75
95
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-desktop-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.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/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"
|
|
@@ -98,7 +98,10 @@ function toolDefinition(ctx) {
|
|
|
98
98
|
worktree,
|
|
99
99
|
cwd: worktree?.path,
|
|
100
100
|
});
|
|
101
|
-
if (result.background)
|
|
101
|
+
if (result.background) {
|
|
102
|
+
if (result.error) return { ok: false, text: result.text, background: true, id: result.id };
|
|
103
|
+
return { ok: true, text: result.text, background: true, id: result.id, worktree };
|
|
104
|
+
}
|
|
102
105
|
const suffix = worktree ? `\nworktree: ${worktree.branch} → ${worktree.path}` : "";
|
|
103
106
|
return { ok: true, text: `project_agent ${name} (${result.stopReason}):\n${result.text}${suffix}`, worktree };
|
|
104
107
|
} catch (error) {
|
|
@@ -9,13 +9,18 @@ import path from "node:path";
|
|
|
9
9
|
|
|
10
10
|
const LIMIT = 100;
|
|
11
11
|
const PREVIEW = 2_000;
|
|
12
|
+
const SECRET = /(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|Bearer\s+[A-Za-z0-9._~+/-]{10,}|(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s,;]+)/giu;
|
|
13
|
+
|
|
14
|
+
export function redact(value) {
|
|
15
|
+
return String(value ?? "").replace(SECRET, "[redacted]");
|
|
16
|
+
}
|
|
12
17
|
|
|
13
18
|
export function runsPath(projectRoot) {
|
|
14
19
|
return path.join(projectRoot, ".dsh", "agents", "runs.json");
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
function clip(value, max = PREVIEW) {
|
|
18
|
-
const text =
|
|
23
|
+
const text = redact(value);
|
|
19
24
|
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
20
25
|
}
|
|
21
26
|
|
|
@@ -29,7 +29,18 @@ export function gitRoot(cwd) {
|
|
|
29
29
|
if (!cwd) throw new Error("worktree: cwd is required");
|
|
30
30
|
const root = tryRun(cwd, ["rev-parse", "--show-toplevel"]);
|
|
31
31
|
if (!root) throw new Error(`worktree: not a git repository (${cwd})`);
|
|
32
|
-
return root;
|
|
32
|
+
return path.resolve(root);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Always anchor managed worktrees to the main worktree. Running from a linked
|
|
37
|
+
* worktree must not create nested `.dsh/worktrees` inside it.
|
|
38
|
+
*/
|
|
39
|
+
export function repoRoot(cwd) {
|
|
40
|
+
const current = gitRoot(cwd);
|
|
41
|
+
const porcelain = tryRun(current, ["worktree", "list", "--porcelain"]) ?? "";
|
|
42
|
+
const first = porcelain.split(/\r?\n/u).find((line) => line.startsWith("worktree "));
|
|
43
|
+
return first ? path.resolve(first.slice("worktree ".length)) : current;
|
|
33
44
|
}
|
|
34
45
|
|
|
35
46
|
export function validateSlug(value) {
|
|
@@ -56,7 +67,7 @@ function ensureExcluded(repo) {
|
|
|
56
67
|
}
|
|
57
68
|
|
|
58
69
|
export function listWorktrees({ cwd }) {
|
|
59
|
-
const repo =
|
|
70
|
+
const repo = repoRoot(cwd);
|
|
60
71
|
const output = run(repo, ["worktree", "list", "--porcelain"]);
|
|
61
72
|
const records = [];
|
|
62
73
|
let current = {};
|
|
@@ -76,14 +87,19 @@ export function listWorktrees({ cwd }) {
|
|
|
76
87
|
}
|
|
77
88
|
if (current.path) records.push(current);
|
|
78
89
|
const root = worktreesRoot(repo);
|
|
90
|
+
const insideManaged = (value) => {
|
|
91
|
+
const relative = path.relative(root, path.resolve(value));
|
|
92
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
93
|
+
};
|
|
79
94
|
return records
|
|
80
|
-
.filter((record) => record.path === repo || record.path
|
|
95
|
+
.filter((record) => path.resolve(record.path) === path.resolve(repo) || insideManaged(record.path) || record.branch?.startsWith("dsh/"))
|
|
81
96
|
.map((record) => {
|
|
82
|
-
const
|
|
83
|
-
const
|
|
97
|
+
const recordPath = path.resolve(record.path);
|
|
98
|
+
const isMain = recordPath === path.resolve(repo);
|
|
99
|
+
const dirty = isMain ? null : (tryRun(recordPath, ["status", "--porcelain"]) ?? "").length > 0;
|
|
84
100
|
return {
|
|
85
|
-
id: path.basename(
|
|
86
|
-
path:
|
|
101
|
+
id: path.basename(recordPath),
|
|
102
|
+
path: recordPath,
|
|
87
103
|
branch: record.branch ?? null,
|
|
88
104
|
head: record.head ?? null,
|
|
89
105
|
detached: record.detached === true,
|
|
@@ -97,7 +113,7 @@ export function listWorktrees({ cwd }) {
|
|
|
97
113
|
}
|
|
98
114
|
|
|
99
115
|
export function createWorktree({ cwd, slug, base }) {
|
|
100
|
-
const repo =
|
|
116
|
+
const repo = repoRoot(cwd);
|
|
101
117
|
const name = validateSlug(slug);
|
|
102
118
|
ensureExcluded(repo);
|
|
103
119
|
const target = path.join(worktreesRoot(repo), name);
|
|
@@ -120,7 +136,7 @@ export function createWorktree({ cwd, slug, base }) {
|
|
|
120
136
|
}
|
|
121
137
|
|
|
122
138
|
export function removeWorktree({ cwd, id, force = false }) {
|
|
123
|
-
const repo =
|
|
139
|
+
const repo = repoRoot(cwd);
|
|
124
140
|
const name = validateSlug(id);
|
|
125
141
|
const target = path.join(worktreesRoot(repo), name);
|
|
126
142
|
const record = listWorktrees({ cwd: repo }).find((item) => path.resolve(item.path) === path.resolve(target));
|
|
@@ -133,10 +149,11 @@ export function removeWorktree({ cwd, id, force = false }) {
|
|
|
133
149
|
}
|
|
134
150
|
|
|
135
151
|
export function worktreeSummary({ cwd }) {
|
|
136
|
-
const
|
|
152
|
+
const repo = repoRoot(cwd);
|
|
153
|
+
const list = listWorktrees({ cwd: repo });
|
|
137
154
|
return {
|
|
138
|
-
repo
|
|
139
|
-
root: worktreesRoot(
|
|
155
|
+
repo,
|
|
156
|
+
root: worktreesRoot(repo),
|
|
140
157
|
worktrees: list.filter((item) => !item.main),
|
|
141
158
|
main: list.find((item) => item.main) ?? null,
|
|
142
159
|
};
|
|
@@ -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() });
|
|
@@ -110,12 +110,14 @@ class HttpTransport {
|
|
|
110
110
|
const controller = new AbortController();
|
|
111
111
|
const timer = setTimeout(() => controller.abort(new Error("timeout")), timeoutMs);
|
|
112
112
|
try {
|
|
113
|
+
const token = typeof this.config.tokenProvider === "function" ? await this.config.tokenProvider() : "";
|
|
113
114
|
const response = await fetch(this.config.url, {
|
|
114
115
|
method: "POST",
|
|
115
116
|
headers: {
|
|
116
117
|
"content-type": "application/json",
|
|
117
118
|
accept: "application/json, text/event-stream",
|
|
118
119
|
...(this.sessionId ? { "mcp-session-id": this.sessionId } : {}),
|
|
120
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
119
121
|
...this.config.headers,
|
|
120
122
|
},
|
|
121
123
|
body: JSON.stringify({ jsonrpc: "2.0", id: makeId(), method, params: params ?? {} }),
|
|
@@ -2,6 +2,7 @@
|
|
|
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";
|
|
5
6
|
|
|
6
7
|
function sanitize(value) {
|
|
7
8
|
return String(value ?? "").replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 48);
|
|
@@ -45,7 +46,10 @@ export class McpManager {
|
|
|
45
46
|
if (this.closed) throw new Error("MCP manager is closed");
|
|
46
47
|
const existing = this.clients.get(server.id);
|
|
47
48
|
if (existing?.client?.connected) return existing;
|
|
48
|
-
const client = new McpClient(
|
|
49
|
+
const client = new McpClient({
|
|
50
|
+
...server,
|
|
51
|
+
tokenProvider: server.url ? () => getAccessToken(server.id, { resource: server.url }).catch(() => null) : undefined,
|
|
52
|
+
}, this.ctx.logger);
|
|
49
53
|
try {
|
|
50
54
|
await client.connect();
|
|
51
55
|
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
|