Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix: surface safe MCP OAuth failures and upgrade installed helpers (#1137)

Hairya1f2bc08d6eb
diff --git a/package.json b/package.json
index 8498e528..779f5196 100644
--- a/package.json
+++ b/package.json
@@ -135,6 +135,7 @@
"@genapi/core": "catalog:",
"@genapi/presets": "catalog:",
"@genapi/shared": "catalog:",
+ "@modelcontextprotocol/client": "catalog:",
"@shikijs/langs": "catalog:testing",
"@tailwindcss/postcss": "catalog:build",
"@tailwindcss/vite": "catalog:build",
diff --git a/packages/dsh-tauri-extension/src/host/server/index.test.ts b/packages/dsh-tauri-extension/src/host/server/index.test.ts
index 38f4522f..5e8a2c3e 100644
--- a/packages/dsh-tauri-extension/src/host/server/index.test.ts
+++ b/packages/dsh-tauri-extension/src/host/server/index.test.ts
@@ -263,6 +263,25 @@ describe('能力管理器路由声明', () => {
expect(missing.status).toBe(400)
})
+ it('授权启动的已知协议错误返回 422 且保留安全诊断', async () => {
+ const { base } = await start()
+ vi.spyOn(mcp, 'peek').mockReturnValue([{ id: 'figma', serverName: 'figma', transport: 'streamable-http', disabled: false, url: 'https://mcp.example.test/mcp' }])
+ const message = 'MCP OAuth client registration failed (HTTP 403). The server may require an approved MCP client.'
+ vi.spyOn(mcpAuth, 'start').mockRejectedValue(Object.assign(new Error(message), { code: 'MCP_OAUTH_START_FAILED' }))
+ const response = await fetch(`${base}${P}/mcp/authorize`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: 'figma' }) })
+ expect(response.status).toBe(422)
+ expect(await response.json()).toEqual({ error: message })
+ })
+
+ it('未知授权错误仍返回 500 且不泄露原始异常中的秘密', async () => {
+ const { base } = await start()
+ vi.spyOn(mcp, 'peek').mockReturnValue([{ id: 'figma', serverName: 'figma', transport: 'streamable-http', disabled: false, url: 'https://mcp.example.test/mcp' }])
+ vi.spyOn(mcpAuth, 'start').mockRejectedValue(new Error('client_secret=secret-marker code_verifier=secret-marker access_token=secret-marker refresh_token=secret-marker https://auth.example.test/?code=secret-marker'))
+ const response = await fetch(`${base}${P}/mcp/authorize`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: 'figma' }) })
+ expect(response.status).toBe(500)
+ expect(await response.json()).toEqual({ error: 'MCP OAuth authorization could not start' })
+ })
+
it('拒绝未知授权任务和不存在的 MCP,stdio 不进入 OAuth', async () => {
const { base } = await start()
const unknown = await fetch(`${base}${P}/mcp/authorize?attemptId=missing`)
diff --git a/packages/dsh-tauri-extension/src/host/server/routes/mcp/authorize/post.ts b/packages/dsh-tauri-extension/src/host/server/routes/mcp/authorize/post.ts
index e3e198cb..9b5283b2 100644
--- a/packages/dsh-tauri-extension/src/host/server/routes/mcp/authorize/post.ts
+++ b/packages/dsh-tauri-extension/src/host/server/routes/mcp/authorize/post.ts
@@ -27,7 +27,8 @@ export default defineEventHandler<EventHandlerRequest, Promise<{ authorizationUr
return await mcpAuth.start(row)
}
catch (error) {
- event.res.status = 500
- return { error: error instanceof Error ? error.message : String(error) }
+ const expected = error instanceof Error && 'code' in error && error.code === 'MCP_OAUTH_START_FAILED'
+ event.res.status = expected ? 422 : 500
+ return { error: expected ? error.message : 'MCP OAuth authorization could not start' }
}
})
diff --git a/packages/dsh-tauri-extension/src/host/service/mcp-oauth.integration.test.mjs b/packages/dsh-tauri-extension/src/host/service/mcp-oauth.integration.test.mjs
new file mode 100644
index 00000000..1ab2ffee
--- /dev/null
+++ b/packages/dsh-tauri-extension/src/host/service/mcp-oauth.integration.test.mjs
@@ -0,0 +1,343 @@
+import { createHash } from 'node:crypto'
+import { createServer } from 'node:http'
+import * as sdk from '@modelcontextprotocol/client'
+import { afterEach, expect, it } from 'vitest'
+import { desktopMcpOAuth } from '../../../../../src-tauri/src/service/patch/mcp_oauth.mjs'
+
+const fixtures = []
+const pending = []
+const secret = 'access_token=private-access refresh_token=private-refresh client_secret=private-client code_verifier=private-verifier'
+const registrationFailure = 'MCP OAuth client registration failed (HTTP 403). The server may require an approved MCP client.'
+
+afterEach(async () => {
+ try {
+ for (const { api, started } of pending.splice(0)) {
+ if (api.lookup(started.attemptId)?.status !== 'pending')
+ continue
+ const callback = callbackUrl(started)
+ callback.searchParams.delete('code')
+ callback.searchParams.set('error', 'access_denied')
+ expect((await fetch(callback)).status).toBe(400)
+ }
+ }
+ finally {
+ await Promise.all(fixtures.splice(0).map(async (fixture) => {
+ await fixture.close()
+ expect(fixture.errors).toEqual([])
+ }))
+ }
+})
+
+function credentials() {
+ const records = new Map()
+ const locks = new Map()
+ return {
+ records,
+ async readRecord(key) {
+ return structuredClone(records.get(key))
+ },
+ modifyRecord(key, update) {
+ const run = (locks.get(key) ?? Promise.resolve()).then(async () => {
+ const next = await update(structuredClone(records.get(key)))
+ if (next !== undefined)
+ records.set(key, structuredClone(next))
+ return structuredClone(records.get(key))
+ })
+ locks.set(key, run.catch(() => {}))
+ return run
+ },
+ }
+}
+
+async function fixture(options = {}) {
+ const requests = []
+ const errors = []
+ let origin
+ let registration
+ let challenge
+ const reply = (res, status, body, headers = {}) => {
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers })
+ res.end(JSON.stringify(body))
+ }
+ const server = createServer(async (req, res) => {
+ try {
+ let raw = ''
+ for await (const chunk of req)
+ raw += chunk
+ const url = new URL(req.url, origin)
+ requests.push({ method: req.method, path: url.pathname, headers: req.headers, body: raw })
+ if (url.pathname === '/.well-known/oauth-protected-resource') {
+ reply(res, 200, { resource: `${origin}/mcp`, authorization_servers: [origin], scopes_supported: ['tools:read'] })
+ return
+ }
+ if (url.pathname === '/.well-known/oauth-authorization-server') {
+ reply(res, options.metadataStatus ?? 200, options.metadataStatus
+ ? { error: secret }
+ : {
+ issuer: origin,
+ authorization_endpoint: `${origin}/authorize`,
+ token_endpoint: `${origin}/token`,
+ registration_endpoint: `${origin}/register`,
+ response_types_supported: ['code'],
+ grant_types_supported: ['authorization_code', 'refresh_token'],
+ token_endpoint_auth_methods_supported: ['none'],
+ code_challenge_methods_supported: ['S256'],
+ authorization_response_iss_parameter_supported: true,
+ })
+ return
+ }
+ if (url.pathname === '/register' && req.method === 'POST') {
+ registration = JSON.parse(raw)
+ reply(res, options.registrationStatus ?? 201, options.registrationStatus ? { error: 'invalid_client_metadata', error_description: secret } : { ...registration, client_id: 'local-desktop' })
+ return
+ }
+ if (url.pathname === '/authorize' && req.method === 'GET') {
+ challenge = url.searchParams.get('code_challenge')
+ const callback = new URL(url.searchParams.get('redirect_uri'))
+ callback.searchParams.set('state', url.searchParams.get('state'))
+ callback.searchParams.set('code', 'valid-local-code')
+ callback.searchParams.set('iss', origin)
+ res.writeHead(302, { Location: callback.href }).end()
+ return
+ }
+ if (url.pathname === '/token' && req.method === 'POST') {
+ const params = new URLSearchParams(raw)
+ const verifier = params.get('code_verifier')
+ const actual = createHash('sha256').update(verifier ?? '').digest('base64url')
+ if (params.get('grant_type') !== 'authorization_code' || params.get('code') !== 'valid-local-code' || params.get('client_id') !== 'local-desktop' || params.get('redirect_uri') !== registration.redirect_uris[0] || !challenge || actual !== challenge) {
+ reply(res, 400, { error: 'invalid_grant' })
+ return
+ }
+ reply(res, options.tokenStatus ?? 200, options.tokenStatus ? { error: 'server_error', error_description: secret } : { access_token: 'local-access', refresh_token: 'local-refresh', token_type: 'Bearer', expires_in: 3600, scope: 'tools:read' })
+ return
+ }
+ if (url.pathname === '/mcp') {
+ if (req.headers.authorization !== 'Bearer local-access') {
+ reply(res, 401, { error: 'authorization_required' }, { 'WWW-Authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource", scope="tools:read"` })
+ return
+ }
+ if (req.method !== 'POST') {
+ reply(res, 405, { error: 'method_not_allowed' })
+ return
+ }
+ const message = JSON.parse(raw)
+ if (message.method === 'initialize') {
+ reply(res, options.initializationStatus ?? 200, options.initializationStatus ? { error: secret } : { jsonrpc: '2.0', id: message.id, result: { protocolVersion: '2025-11-25', capabilities: {}, serverInfo: { name: 'local-mcp', version: '1' } } })
+ return
+ }
+ if (message.method === 'server/discover') {
+ reply(res, 200, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
+ return
+ }
+ if (message.method === 'notifications/initialized') {
+ res.writeHead(202).end()
+ return
+ }
+ }
+ reply(res, 404, { error: 'not_found' })
+ }
+ catch (error) {
+ errors.push(error.message)
+ reply(res, 500, { error: 'fixture_error' })
+ }
+ })
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ origin = `http://127.0.0.1:${server.address().port}`
+ const value = {
+ origin,
+ requests,
+ errors,
+ row: { serverName: 'local-oauth', transport: 'streamable-http', url: `${origin}/mcp` },
+ get registration() { return registration },
+ async close() {
+ await new Promise((resolve, reject) => {
+ server.close(error => error ? reject(error) : resolve())
+ server.closeAllConnections()
+ })
+ },
+ }
+ fixtures.push(value)
+ return value
+}
+
+async function start(fixture) {
+ const store = credentials()
+ const api = desktopMcpOAuth(sdk, store)
+ const started = await api.start(fixture.row)
+ pending.push({ api, started })
+ return { api, started, store }
+}
+
+function callbackUrl(started) {
+ const authorization = new URL(started.authorizationUrl)
+ const callback = new URL(authorization.searchParams.get('redirect_uri'))
+ callback.searchParams.set('state', authorization.searchParams.get('state'))
+ callback.searchParams.set('code', 'valid-local-code')
+ callback.searchParams.set('iss', authorization.origin)
+ return callback
+}
+
+function expectPrivate(value) {
+ const text = JSON.stringify(value)
+ for (const marker of ['private-access', 'private-refresh', 'private-client', 'private-verifier'])
+ expect(text).not.toContain(marker)
+}
+
+it('reports real SDK registration rejection with a safe actionable error instead of a generic startup failure', async () => {
+ const local = await fixture({ registrationStatus: 403 })
+ const store = credentials()
+ const api = desktopMcpOAuth(sdk, store)
+ const error = await api.start(local.row).then((started) => {
+ pending.push({ api, started })
+ return started
+ }, error => error)
+ expect(error).toBeInstanceOf(Error)
+ expect(error).toMatchObject({ code: 'MCP_OAUTH_START_FAILED', message: registrationFailure })
+ expect(error).not.toHaveProperty('cause')
+ expectPrivate({ ...error, message: error.message, stack: error.stack })
+ expect(local.requests.map(request => `${request.method} ${request.path}`)).toEqual([
+ 'POST /mcp',
+ 'GET /.well-known/oauth-protected-resource',
+ 'GET /.well-known/oauth-authorization-server',
+ 'POST /register',
+ ])
+ expect(local.registration).toMatchObject({ client_name: 'DSH Desktop', application_type: 'native', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', scope: 'tools:read' })
+ expect(local.registration.redirect_uris).toHaveLength(1)
+ expect(local.registration.redirect_uris[0]).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/)
+ expect(store.records.size).toBe(0)
+})
+
+it('reports authorization server metadata HTTP failures without exposing server text or endpoint URLs', async () => {
+ const local = await fixture({ metadataStatus: 503 })
+ const api = desktopMcpOAuth(sdk, credentials())
+ const error = await api.start(local.row).then((started) => {
+ pending.push({ api, started })
+ return started
+ }, error => error)
+ expect(error).toBeInstanceOf(Error)
+ expect(error).toMatchObject({ code: 'MCP_OAUTH_START_FAILED', message: 'MCP OAuth server discovery failed (HTTP 503)' })
+ expect(error).not.toHaveProperty('cause')
+ expectPrivate({ ...error, message: error.message, stack: error.stack })
+ expect(error.message).not.toContain(local.origin)
+ expect(local.requests.map(request => `${request.method} ${request.path}`)).toEqual([
+ 'POST /mcp',
+ 'GET /.well-known/oauth-protected-resource',
+ 'GET /.well-known/oauth-authorization-server',
+ ])
+})
+
+it('completes real SDK discovery registration PKCE callback token exchange and MCP initialization before authorizing', async () => {
+ const local = await fixture()
+ const { api, started, store } = await start(local)
+ const authorization = new URL(started.authorizationUrl)
+ expect(authorization.searchParams.get('state')).toMatch(/^[a-f0-9]{64}$/)
+ expect(authorization.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/)
+ expect(authorization.searchParams.get('code_challenge_method')).toBe('S256')
+ expect(authorization.searchParams.get('client_id')).toBe('local-desktop')
+ expect(authorization.searchParams.get('resource')).toBe(local.row.url)
+ expect(api.lookup(started.attemptId)).toEqual({ status: 'pending' })
+ const response = await fetch(authorization)
+ expect(response.status).toBe(200)
+ expect(await response.text()).toBe('MCP authorized. You can close this window.')
+ expect(api.lookup(started.attemptId)).toEqual({ status: 'authorized' })
+ const record = [...store.records.values()][0].payload
+ expect(record.tokens).toMatchObject({ access_token: 'local-access', refresh_token: 'local-refresh', issuer: local.origin })
+ expect(record.clientInformation).toMatchObject({ client_id: 'local-desktop', issuer: local.origin })
+ expect(record.discovery.authorizationServerMetadata.issuer).toBe(local.origin)
+ expect(record.redirectUrl).toBe(authorization.searchParams.get('redirect_uri'))
+ expect(record).not.toHaveProperty('verifier')
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(1)
+ const initialized = local.requests.filter(request => request.path === '/mcp' && request.method === 'POST' && request.headers.authorization === 'Bearer local-access').map(request => JSON.parse(request.body).method)
+ expect(initialized).toContain('initialize')
+ expect(initialized).toContain('notifications/initialized')
+})
+
+it('rejects wrong and duplicate callback state without consuming the real SDK authorization attempt', async () => {
+ const local = await fixture()
+ const { api, started } = await start(local)
+ const callback = callbackUrl(started)
+ callback.searchParams.set('state', 'incorrect')
+ expect((await fetch(callback)).status).toBe(400)
+ expect(api.lookup(started.attemptId)).toEqual({ status: 'pending' })
+ callback.searchParams.set('state', new URL(started.authorizationUrl).searchParams.get('state'))
+ callback.searchParams.append('state', 'duplicate')
+ expect((await fetch(callback)).status).toBe(400)
+ expect(api.lookup(started.attemptId)).toEqual({ status: 'pending' })
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(0)
+ expect((await fetch(started.authorizationUrl)).status).toBe(200)
+ expect(api.lookup(started.attemptId)).toEqual({ status: 'authorized' })
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(1)
+})
+
+it('never reports authorized when real SDK token exchange succeeds but MCP initialization fails', async () => {
+ const local = await fixture({ initializationStatus: 500 })
+ const { api, started } = await start(local)
+ const response = await fetch(started.authorizationUrl)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('MCP authorization failed. Return to DSH for details.')
+ const status = api.lookup(started.attemptId)
+ expect(status).toEqual({ status: 'error', error: 'MCP initialization failed (HTTP 500)' })
+ expectPrivate(status)
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(1)
+})
+
+it('reports authorization required instead of token failure when post-token MCP initialization still returns 401', async () => {
+ const local = await fixture({ initializationStatus: 401 })
+ const { api, started } = await start(local)
+ const response = await fetch(started.authorizationUrl)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('MCP authorization failed. Return to DSH for details.')
+ const status = api.lookup(started.attemptId)
+ expect(status).toEqual({ status: 'error', error: 'MCP authorization required' })
+ expectPrivate(status)
+ const tokenGrants = local.requests.filter(request => request.path === '/token').map(request => new URLSearchParams(request.body).get('grant_type'))
+ expect(tokenGrants).toEqual(['authorization_code', 'refresh_token'])
+})
+
+it('reports real SDK token exchange HTTP failures without exposing OAuth server error descriptions', async () => {
+ const local = await fixture({ tokenStatus: 503 })
+ const { api, started, store } = await start(local)
+ const response = await fetch(started.authorizationUrl)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('MCP authorization failed. Return to DSH for details.')
+ const status = api.lookup(started.attemptId)
+ expect(status).toEqual({ status: 'error', error: 'MCP OAuth token exchange failed (HTTP 503)' })
+ expectPrivate(status)
+ expect(store.records.size).toBe(0)
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(1)
+})
+
+it('denies a real SDK callback without exchanging tokens or exposing callback error text', async () => {
+ const local = await fixture()
+ const { api, started, store } = await start(local)
+ const callback = callbackUrl(started)
+ callback.searchParams.delete('code')
+ callback.searchParams.set('error', 'access_denied')
+ callback.searchParams.set('error_description', secret)
+ const response = await fetch(callback)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('MCP authorization failed. Return to DSH for details.')
+ const status = api.lookup(started.attemptId)
+ expect(status).toEqual({ status: 'error', error: 'OAuth authorization denied' })
+ expectPrivate(status)
+ expect(store.records.size).toBe(0)
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(0)
+})
+
+it('preserves callback issuer validation and never redeems a code from a mismatched issuer', async () => {
+ const local = await fixture()
+ const { api, started } = await start(local)
+ const callback = callbackUrl(started)
+ callback.searchParams.set('iss', 'https://attacker.invalid/private-access')
+ const response = await fetch(callback)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('MCP authorization failed. Return to DSH for details.')
+ const status = api.lookup(started.attemptId)
+ expect(status).toEqual({ status: 'error', error: 'MCP OAuth authorization server validation failed' })
+ expectPrivate(status)
+ expect(JSON.stringify(status)).not.toContain('attacker.invalid')
+ expect(local.requests.filter(request => request.path === '/token')).toHaveLength(0)
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 84b3058a..27e3be1e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -56,6 +56,9 @@ catalogs:
'@genapi/shared':
specifier: ^4.1.4
version: 4.1.4
+ '@modelcontextprotocol/client':
+ specifier: 2.2.0
+ version: 2.2.0
'@tauri-apps/plugin-os':
specifier: ^2.3.2
version: 2.3.2
@@ -775,6 +778,9 @@ importers:
'@genapi/shared':
specifier: 'catalog:'
version: 4.1.4
+ '@modelcontextprotocol/client':
+ specifier: 'catalog:'
+ version: 2.2.0
'@shikijs/langs':
specifier: catalog:testing
version: 4.3.1
@@ -3342,6 +3348,14 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-LxCou/CSYQ6dwEnjhLZY0KnEuc8V4UJ3IEQCl/uR2yHobSQIEdJKUlKLRYRF5i5FqRGHy1eK7une3aAWDHLtig==}
+ engines: {node: '>=20'}
+
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw==}
+ engines: {node: '>=20'}
+
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -6286,6 +6300,14 @@ packages:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
+ resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==}
+ engines: {node: '>=18.0.0'}
+
+ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'}
@@ -7116,6 +7138,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
+ resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
+
resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
@@ -8181,6 +8206,10 @@ packages:
resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}
+ engines: {node: '>=16.20.0'}
+
resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
@@ -12069,6 +12098,20 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ '@modelcontextprotocol/core': 2.2.0
+ cross-spawn: 7.0.6
+ eventsource: 3.0.7
+ eventsource-parser: 3.1.1
+ jose: 6.2.12
+ pkce-challenge: 5.0.1
+ zod: 4.4.3
+
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ zod: 4.4.3
+
'@napi-rs/[email protected]':
optional: true
@@ -15070,6 +15113,12 @@ snapshots:
+
+ dependencies:
+ eventsource-parser: 3.1.1
+
@@ -15947,6 +15996,8 @@ snapshots:
+
@@ -17383,6 +17434,8 @@ snapshots:
+
dependencies:
confbox: 0.1.8
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 8b8d77c7..d42bc2cc 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -119,6 +119,7 @@ catalog:
'@genapi/pipeline': ^4.1.4
'@genapi/presets': ^4.1.4
'@genapi/shared': ^4.1.4
+ '@modelcontextprotocol/client': 2.2.0
'@tauri-apps/plugin-os': ^2.3.2
'@tauri-apps/plugin-store': ^2.4.4
dsh-h3: 0.2.1
diff --git a/src-tauri/src/service/patch/mcp_oauth.mjs b/src-tauri/src/service/patch/mcp_oauth.mjs
index 41d321e7..199c71de 100644
--- a/src-tauri/src/service/patch/mcp_oauth.mjs
+++ b/src-tauri/src/service/patch/mcp_oauth.mjs
@@ -159,14 +159,46 @@ export function desktopMcpOAuth(sdk, credentials) {
let timer
let transport
let listener
- const finish = (error) => {
+ let stage = 'MCP initialization'
+ let httpStatus
+ const request = async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : input)
+ const metadata = interaction.discovery?.authorizationServerMetadata
+ const authorizationServer = interaction.discovery?.authorizationServerUrl
+ if (url.href === metadata?.registration_endpoint || (!metadata && authorizationServer && url.href === new URL('/register', authorizationServer).href))
+ stage = 'MCP OAuth client registration'
+ else if (url.href === metadata?.token_endpoint || (!metadata && authorizationServer && url.href === new URL('/token', authorizationServer).href))
+ stage = 'MCP OAuth token exchange'
+ else
+ stage = url.href === endpoint(row).href ? 'MCP initialization' : 'MCP OAuth server discovery'
+ httpStatus = undefined
+ const response = await fetchWithin(controller.signal)(input, init)
+ httpStatus = response.status
+ return response
+ }
+ const failure = (error) => {
+ if ((sdk.IssuerMismatchError && error instanceof sdk.IssuerMismatchError) || (sdk.AuthorizationServerMismatchError && error instanceof sdk.AuthorizationServerMismatchError))
+ return 'MCP OAuth authorization server validation failed'
+ if (sdk.InsecureTokenEndpointError && error instanceof sdk.InsecureTokenEndpointError)
+ return 'MCP OAuth requires a secure token endpoint'
+ if (error instanceof Error && /^(?:MCP authorization timed out|MCP authorization required|OAuth authorization denied|Missing OAuth authorization code|MCP server did not request OAuth authorization|MCP initialization failed(?: \(HTTP [45]\d{2}\))?)$/.test(error.message))
+ return error.message
+ const status = Number.isInteger(httpStatus) && httpStatus >= 400 && httpStatus <= 599 ? ` (HTTP ${httpStatus})` : ''
+ if (sdk.RegistrationRejectedError && error instanceof sdk.RegistrationRejectedError)
+ return `MCP OAuth client registration failed${status}${httpStatus === 403 ? '. The server may require an approved MCP client.' : ''}`
+ const metadata = interaction.discovery?.authorizationServerMetadata
+ if (metadata && !metadata.registration_endpoint && !interaction.clientInformation)
+ return 'MCP OAuth client registration is not supported by the server'
+ return `${stage} failed${status}`
+ }
+ const finish = (message) => {
clearTimeout(timer)
controller.abort()
listener.close()
listener.closeAllConnections()
- if (error) {
+ if (message) {
attempt.status = 'error'
- attempt.error = error instanceof Error && ['MCP authorization timed out', 'OAuth authorization denied', 'Missing OAuth authorization code', 'MCP initialization failed'].some(prefix => error.message.startsWith(prefix)) ? error.message : 'MCP authorization failed'
+ attempt.error = message
}
interaction.verifier = undefined
interaction.state = undefined
@@ -204,7 +236,7 @@ export function desktopMcpOAuth(sdk, credentials) {
}
catch (error) {
res.writeHead(400).end('MCP authorization failed. Return to DSH for details.')
- finish(error)
+ finish(failure(error))
}
})
await new Promise((resolve, reject) => {
@@ -213,10 +245,10 @@ export function desktopMcpOAuth(sdk, credentials) {
})
interaction.redirectUrl = `http://127.0.0.1:${listener.address().port}/callback`
attempts.set(attemptId, attempt)
- timer = setTimeout(() => finish(new Error('MCP authorization timed out')), 300000)
+ timer = setTimeout(finish, 300000, 'MCP authorization timed out')
timer.unref()
try {
- transport = new sdk.StreamableHTTPClientTransport(endpoint(row), { authProvider: provider(row, interaction, controller.signal), requestInit: { headers: row.headers }, fetch: fetchWithin(controller.signal) })
+ transport = new sdk.StreamableHTTPClientTransport(endpoint(row), { authProvider: provider(row, interaction, controller.signal), requestInit: { headers: row.headers }, fetch: request })
const client = new sdk.Client({ name: 'dsh-desktop-auth', version: '1' })
try {
await client.connect(transport, { signal: AbortSignal.timeout(15000), timeout: 15000 })
@@ -233,8 +265,9 @@ export function desktopMcpOAuth(sdk, credentials) {
return { authorizationUrl: interaction.authorizationUrl, attemptId }
}
catch (error) {
- finish(error)
- throw new Error('MCP OAuth authorization could not start')
+ const message = failure(error)
+ finish(message)
+ throw Object.assign(new Error(message), { code: 'MCP_OAUTH_START_FAILED' })
}
}
const api = { provider, check, start, lookup: id => attempts.get(id) ? { ...attempts.get(id) } : undefined }
diff --git a/src-tauri/src/service/patch/mcp_startup.rs b/src-tauri/src/service/patch/mcp_startup.rs
index aba16aca..6314cf6a 100644
--- a/src-tauri/src/service/patch/mcp_startup.rs
+++ b/src-tauri/src/service/patch/mcp_startup.rs
@@ -1,3 +1,4 @@
+use sha2::{Digest, Sha256};
use std::path::Path;
use crate::utils::{patch_core_file, patch_dsh, PatchOutcome};
@@ -17,8 +18,48 @@ const TRANSPORT_ANCHOR: &str = "case \"streamable-http\": return new StreamableH
const TRANSPORT_PATCHED: &str = "case \"streamable-http\": return new StreamableHTTPClientTransport(new URL(config.url), { authProvider: desktopMcpOAuth(desktopMcpSdk, credentials).provider(config), requestInit: { headers: config.headers } });";
fn patch_source(source: &str) -> PatchOutcome {
- if source.contains(OAUTH_SOURCE) && source.contains(TRANSPORT_PATCHED) {
- return PatchOutcome::AlreadyPatched;
+ if source.contains(OAUTH_IMPORT) || source.contains("desktopMcpOAuth") {
+ let Some(start) = source.find(
+ "\nimport { createHash as oauthHash, randomBytes as oauthRandom } from 'node:crypto'\n",
+ ) else {
+ return PatchOutcome::AnchorMissing;
+ };
+ let (prefix, helper) = source.split_at(start + 1);
+ if !prefix.starts_with(OAUTH_IMPORT)
+ || [
+ OAUTH_IMPORT,
+ TRANSPORT_PATCHED,
+ READY_PATCHED,
+ "function createTransport(config, credentials) {",
+ "const inject = [\"tools\", \"credentials\"];",
+ ]
+ .iter()
+ .any(|anchor| prefix.matches(anchor).count() != 1)
+ || prefix
+ .matches("transport = createTransport(config, ctx.credentials);")
+ .count()
+ + prefix
+ .matches("generation.connect(createTransport(config, ctx.credentials));")
+ .count()
+ != 1
+ || source
+ .matches("export function desktopMcpOAuth(sdk, credentials) {")
+ .count()
+ != 1
+ {
+ return PatchOutcome::AnchorMissing;
+ }
+ if helper == OAUTH_SOURCE {
+ return PatchOutcome::AlreadyPatched;
+ }
+ // #1101 已覆盖原始锚点,只替换完整已知尾部,拒绝未知追加源码。
+ return if format!("{:x}", Sha256::digest(helper.as_bytes()))
+ == "d2f9d978bb36c9324556af502fa92a45fe83e72818427b4d9969b8a23b376974"
+ {
+ PatchOutcome::Patched(format!("{prefix}{OAUTH_SOURCE}"))
+ } else {
+ PatchOutcome::AnchorMissing
+ };
}
if !source.contains(READY_ANCHOR)
|| !source.contains(TRANSPORT_ANCHOR)
@@ -78,6 +119,143 @@ pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
mod tests {
use super::*;
+ const OAUTH_1101: &str = include_str!("../../../../test/fixtures/mcp-oauth-1101.mjs");
+
+ fn oauth_prefix(call: &str) -> String {
+ r#"import * as desktopMcpSdk from "@modelcontextprotocol/client";
+function createTransport(config, credentials) {
+case "streamable-http": return new StreamableHTTPClientTransport(new URL(config.url), { authProvider: desktopMcpOAuth(desktopMcpSdk, credentials).provider(config), requestInit: { headers: config.headers } });
+}
+__CONNECT__
+const inject = ["tools", "credentials"];
+ctx.effect(() => dispose, "mcp-client.connection");
+ // issue #1022: non-strict MCP connections must not block Host readiness.
+ if (!config.failOnStartupError) {
+ connection.ready.catch((error) => ctx.logger.error(`mcp-client(${config.serverName}): background startup failed: ${String(error)}`));
+ return;
+ }
+ const outcome = await connection.ready;
+if (outcome.error !== void 0 && config.failOnStartupError) throw outcome.error;
+export { activate, inject };
+"#
+ .replace("__CONNECT__", call)
+ }
+
+ #[test]
+ fn oauth_upgrade_fixture_matches_the_1101_release() {
+ assert_eq!(
+ format!("{:x}", Sha256::digest(OAUTH_1101.as_bytes())),
+ "d2f9d978bb36c9324556af502fa92a45fe83e72818427b4d9969b8a23b376974"
+ );
+ }
+
+ #[test]
+ fn upgrades_1101_oauth_helper_without_changing_core_wiring() {
+ assert!(
+ OAUTH_1101 != OAUTH_SOURCE,
+ "upgrade requires a newer OAuth helper"
+ );
+ for call in [
+ "transport = createTransport(config, ctx.credentials);",
+ "generation.connect(createTransport(config, ctx.credentials));",
+ ] {
+ let prefix = oauth_prefix(call);
+ let source = format!("{prefix}{OAUTH_1101}");
+ let outcome = patch_source(&source);
+ let PatchOutcome::Patched(patched) = outcome else {
+ panic!("expected #1101 helper upgrade for {call}, got {outcome:?}");
+ };
+ assert_eq!(patched, format!("{prefix}{OAUTH_SOURCE}"));
+ assert_eq!(patched.matches(OAUTH_SOURCE).count(), 1);
+ assert!(!patched.contains(OAUTH_1101));
+ assert_eq!(patch_source(&patched), PatchOutcome::AlreadyPatched);
+ }
+ }
+
+ #[test]
+ fn current_oauth_helper_is_idempotent_with_complete_wiring() {
+ let source = format!(
+ "{}{OAUTH_SOURCE}",
+ oauth_prefix("transport = createTransport(config, ctx.credentials);")
+ );
+ assert_eq!(patch_source(&source), PatchOutcome::AlreadyPatched);
+ }
+
+ #[test]
+ fn oauth_patches_reject_missing_or_duplicate_wiring() {
+ for helper in [OAUTH_1101, OAUTH_SOURCE] {
+ let source = format!(
+ "{}{helper}",
+ oauth_prefix("transport = createTransport(config, ctx.credentials);")
+ );
+ for anchor in [
+ "import * as desktopMcpSdk from \"@modelcontextprotocol/client\";\n",
+ "function createTransport(config, credentials) {",
+ "case \"streamable-http\": return new StreamableHTTPClientTransport(new URL(config.url), { authProvider: desktopMcpOAuth(desktopMcpSdk, credentials).provider(config), requestInit: { headers: config.headers } });",
+ "transport = createTransport(config, ctx.credentials);",
+ "const inject = [\"tools\", \"credentials\"];",
+ READY_PATCHED,
+ "export function desktopMcpOAuth(sdk, credentials) {",
+ ] {
+ assert_eq!(
+ patch_source(&source.replacen(anchor, "", 1)),
+ PatchOutcome::AnchorMissing,
+ "missing anchor: {anchor}"
+ );
+ assert_eq!(
+ patch_source(&source.replacen(anchor, &format!("{anchor}\n{anchor}"), 1)),
+ PatchOutcome::AnchorMissing,
+ "duplicate anchor: {anchor}"
+ );
+ }
+ assert_eq!(
+ patch_source(&format!("const upstream = true;\n{source}")),
+ PatchOutcome::AnchorMissing
+ );
+ assert_eq!(
+ patch_source(&source.replacen(
+ "transport = createTransport(config, ctx.credentials);",
+ "transport = createTransport(config, ctx.credentials);\ngeneration.connect(createTransport(config, ctx.credentials));",
+ 1
+ )),
+ PatchOutcome::AnchorMissing
+ );
+ }
+ }
+
+ #[test]
+ fn oauth_patches_reject_unknown_or_unbounded_helpers() {
+ for helper in [OAUTH_1101, OAUTH_SOURCE] {
+ let prefix = oauth_prefix("transport = createTransport(config, ctx.credentials);");
+ for (case, tail) in [
+ (
+ "trailing declaration",
+ format!("{helper}\nconst upstream = 1;\n"),
+ ),
+ (
+ "trailing function",
+ format!("{helper}\nfunction upstream() {{}}\n"),
+ ),
+ ("duplicate helper", format!("{helper}{helper}")),
+ ("trimmed helper", helper.trim_end().to_owned()),
+ ("truncated helper", helper[..helper.len() - 2].to_owned()),
+ (
+ "unknown helper",
+ helper.replace(
+ "const attempts = new Map()",
+ "const attempts = new WeakMap()",
+ ),
+ ),
+ ] {
+ assert_eq!(
+ patch_source(&format!("{prefix}{tail}")),
+ PatchOutcome::AnchorMissing,
+ "unrecognized helper: {case}"
+ );
+ }
+ }
+ }
+
#[test]
fn patch_read_failure_is_reported_before_launch() {
let core = tempfile::tempdir().unwrap();
diff --git a/test/fixtures/mcp-oauth-1101.mjs b/test/fixtures/mcp-oauth-1101.mjs
new file mode 100644
index 00000000..41d321e7
--- /dev/null
+++ b/test/fixtures/mcp-oauth-1101.mjs
@@ -0,0 +1,243 @@
+import { createHash as oauthHash, randomBytes as oauthRandom } from 'node:crypto'
+import { createServer as oauthServer } from 'node:http'
+
+const oauthInstances = new WeakMap()
+
+export function desktopMcpOAuth(sdk, credentials) {
+ if (oauthInstances.has(credentials))
+ return oauthInstances.get(credentials)
+ const attempts = new Map()
+ const endpoint = (row) => {
+ if (row.transport !== 'streamable-http')
+ throw new Error('OAuth requires a streamable HTTP server')
+ const url = new URL(row.url)
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash)
+ throw new Error('Invalid MCP HTTP URL')
+ return url
+ }
+ const keyOf = row => `mcp-client/oauth-${oauthHash('sha256').update(`${row.serverName}\0${endpoint(row).href}`).digest('hex')}`
+ const read = async key => (await credentials.readRecord(key))?.payload ?? {}
+ const write = (key, update) => credentials.modifyRecord(key, async current => ({ kind: 'grant', payload: update(current?.payload ?? {}) }))
+ const fetchWithin = signal => (url, init) => fetch(url, { ...init, signal: AbortSignal.any([AbortSignal.timeout(15000), ...(signal ? [signal] : []), ...(init?.signal ? [init.signal] : [])]) })
+ function provider(row, interaction, signal) {
+ const key = keyOf(row)
+ const make = (load, save, interactive) => ({
+ get redirectUrl() { return interaction?.redirectUrl ?? 'http://127.0.0.1/callback' },
+ get clientMetadata() {
+ return { client_name: 'DSH Desktop', redirect_uris: [this.redirectUrl], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' }
+ },
+ clientInformation: async () => interaction ? interaction.clientInformation : (await load()).clientInformation,
+ saveClientInformation: async (info) => {
+ if (interaction)
+ interaction.clientInformation = info
+ else
+ await save(data => ({ ...data, clientInformation: info }))
+ },
+ discoveryState: async () => interaction?.discovery ?? (await load()).discovery,
+ saveDiscoveryState: async (discovery) => {
+ if (interaction)
+ interaction.discovery = discovery
+ else
+ await save(data => ({ ...data, discovery }))
+ },
+ tokens: async () => (await load()).tokens,
+ saveTokens: tokens => save(data => ({ ...data, tokens, expiresAt: typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined, ...(interaction ? { redirectUrl: interaction.redirectUrl, clientInformation: interaction.clientInformation, discovery: interaction.discovery } : {}) })),
+ state: () => interaction?.state,
+ saveCodeVerifier: async (value) => {
+ if (!interactive)
+ throw new sdk.UnauthorizedError('MCP authorization required')
+ interaction.verifier = value
+ },
+ codeVerifier: () => {
+ if (!interaction?.verifier)
+ throw new Error('Missing OAuth PKCE verifier')
+ return interaction.verifier
+ },
+ redirectToAuthorization: async (url) => {
+ if (!interactive)
+ throw new sdk.UnauthorizedError('MCP authorization required')
+ interaction.authorizationUrl = url.href
+ },
+ invalidateCredentials: async scope => save((data) => {
+ const next = { ...data }
+ delete next.tokens
+ delete next.expiresAt
+ if (scope === 'client')
+ delete next.clientInformation
+ return next
+ }),
+ })
+ const result = make(() => read(key), update => write(key, update), Boolean(interaction))
+ result.tokens = async () => {
+ let data = await read(key)
+ if (data.tokens?.refresh_token && data.expiresAt !== undefined && data.expiresAt <= Date.now() + 30000) {
+ await credentials.modifyRecord(key, async (current) => {
+ let locked = current?.payload ?? {}
+ if (!locked.tokens?.refresh_token || locked.expiresAt === undefined || locked.expiresAt > Date.now() + 30000)
+ return undefined
+ if (!locked.clientInformation)
+ throw new sdk.UnauthorizedError('MCP authorization required')
+ const transaction = make(async () => locked, async (update) => {
+ locked = update(locked)
+ }, false)
+ Object.defineProperty(transaction, 'redirectUrl', { get: () => locked.redirectUrl ?? 'http://127.0.0.1/callback' })
+ await sdk.auth(transaction, { serverUrl: endpoint(row), fetchFn: fetchWithin(signal) })
+ return { kind: 'grant', payload: locked }
+ })
+ data = await read(key)
+ }
+ if (!data.tokens)
+ return undefined
+ const { refresh_token: omitted, ...tokens } = data.tokens
+ return tokens
+ }
+ if (interaction)
+ return result
+ let sentToken
+ return {
+ token: async () => {
+ sentToken = (await result.tokens())?.access_token
+ return sentToken
+ },
+ onUnauthorized: async (context) => {
+ await credentials.modifyRecord(key, async (current) => {
+ let locked = current?.payload ?? {}
+ if (locked.tokens?.access_token && locked.tokens.access_token !== sentToken)
+ return undefined
+ if (!locked.tokens?.refresh_token || !locked.clientInformation)
+ throw new sdk.UnauthorizedError('MCP authorization required')
+ const transaction = make(async () => locked, async (update) => {
+ locked = update(locked)
+ }, false)
+ Object.defineProperty(transaction, 'redirectUrl', { get: () => locked.redirectUrl ?? 'http://127.0.0.1/callback' })
+ const challenge = sdk.extractWWWAuthenticateParams(context.response)
+ await sdk.auth(transaction, { serverUrl: endpoint(row), ...challenge, fetchFn: fetchWithin(signal) })
+ return { kind: 'grant', payload: locked }
+ })
+ },
+ }
+ }
+ async function check(row, timeoutMs = 15000) {
+ let client
+ let transport
+ let unauthorized = false
+ let httpStatus
+ try {
+ const url = endpoint(row)
+ const signal = AbortSignal.timeout(timeoutMs)
+ client = new sdk.Client({ name: 'dsh-desktop-check', version: '1' })
+ transport = new sdk.StreamableHTTPClientTransport(url, {
+ authProvider: provider(row, undefined, signal),
+ requestInit: { headers: row.headers },
+ fetch: async (input, init) => {
+ const response = await fetchWithin(signal)(input, init)
+ httpStatus = response.status
+ unauthorized ||= response.status === 401
+ return response
+ },
+ })
+ await client.connect(transport, { signal, timeout: timeoutMs })
+ return { ok: true }
+ }
+ catch (error) {
+ const requiresAuth = unauthorized || error instanceof sdk.UnauthorizedError || Boolean(sdk.InsufficientScopeError && error instanceof sdk.InsufficientScopeError)
+ return { ok: false, detail: requiresAuth ? 'MCP authorization required' : httpStatus ? `MCP initialization failed (HTTP ${httpStatus})` : 'MCP initialization failed', ...(requiresAuth ? { requiresAuth: true } : {}) }
+ }
+ finally {
+ await Promise.resolve(client?.transport ? client.close() : transport?.close()).catch(() => {})
+ }
+ }
+ async function start(row) {
+ endpoint(row)
+ if ([...attempts.values()].filter(attempt => attempt.status === 'pending').length >= 8)
+ throw new Error('Too many pending MCP authorizations')
+ const attemptId = oauthRandom(32).toString('hex')
+ const interaction = { state: oauthRandom(32).toString('hex') }
+ const attempt = { status: 'pending' }
+ const controller = new AbortController()
+ let consumed = false
+ let timer
+ let transport
+ let listener
+ const finish = (error) => {
+ clearTimeout(timer)
+ controller.abort()
+ listener.close()
+ listener.closeAllConnections()
+ if (error) {
+ attempt.status = 'error'
+ attempt.error = error instanceof Error && ['MCP authorization timed out', 'OAuth authorization denied', 'Missing OAuth authorization code', 'MCP initialization failed'].some(prefix => error.message.startsWith(prefix)) ? error.message : 'MCP authorization failed'
+ }
+ interaction.verifier = undefined
+ interaction.state = undefined
+ setTimeout(() => attempts.delete(attemptId), 300000).unref()
+ }
+ listener = oauthServer(async (req, res) => {
+ res.setHeader('Cache-Control', 'no-store')
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8')
+ let url
+ try {
+ url = new URL(req.url ?? '/', interaction.redirectUrl)
+ }
+ catch {
+ res.writeHead(400).end('Invalid OAuth callback')
+ return
+ }
+ if (req.method !== 'GET' || req.headers.host !== new URL(interaction.redirectUrl).host || url.pathname !== '/callback' || consumed || url.searchParams.getAll('state').length !== 1 || url.searchParams.get('state') !== interaction.state) {
+ res.writeHead(400).end('Invalid OAuth callback')
+ return
+ }
+ consumed = true
+ try {
+ if (url.searchParams.has('error'))
+ throw new Error('OAuth authorization denied')
+ if (url.searchParams.getAll('code').length !== 1 || !url.searchParams.get('code'))
+ throw new Error('Missing OAuth authorization code')
+ await transport.finishAuth(url.searchParams)
+ const result = await check(row)
+ controller.signal.throwIfAborted()
+ if (!result.ok)
+ throw new Error(result.detail ?? 'MCP initialization failed after authorization')
+ attempt.status = 'authorized'
+ res.end('MCP authorized. You can close this window.')
+ finish()
+ }
+ catch (error) {
+ res.writeHead(400).end('MCP authorization failed. Return to DSH for details.')
+ finish(error)
+ }
+ })
+ await new Promise((resolve, reject) => {
+ listener.once('error', reject)
+ listener.listen(0, '127.0.0.1', resolve)
+ })
+ interaction.redirectUrl = `http://127.0.0.1:${listener.address().port}/callback`
+ attempts.set(attemptId, attempt)
+ timer = setTimeout(() => finish(new Error('MCP authorization timed out')), 300000)
+ timer.unref()
+ try {
+ transport = new sdk.StreamableHTTPClientTransport(endpoint(row), { authProvider: provider(row, interaction, controller.signal), requestInit: { headers: row.headers }, fetch: fetchWithin(controller.signal) })
+ const client = new sdk.Client({ name: 'dsh-desktop-auth', version: '1' })
+ try {
+ await client.connect(transport, { signal: AbortSignal.timeout(15000), timeout: 15000 })
+ }
+ catch (error) {
+ if (!interaction.authorizationUrl)
+ throw error
+ }
+ finally {
+ await (client.transport ? client.close() : transport.close()).catch(() => {})
+ }
+ if (!interaction.authorizationUrl)
+ throw new Error('MCP server did not request OAuth authorization')
+ return { authorizationUrl: interaction.authorizationUrl, attemptId }
+ }
+ catch (error) {
+ finish(error)
+ throw new Error('MCP OAuth authorization could not start')
+ }
+ }
+ const api = { provider, check, start, lookup: id => attempts.get(id) ? { ...attempts.get(id) } : undefined }
+ oauthInstances.set(credentials, api)
+ return api
+}