universal-plugin-hub 1.0.6 → 1.0.12

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.
@@ -0,0 +1,270 @@
1
+ import { createServer } from 'node:http'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { spawn } from 'node:child_process'
4
+ import { once } from 'node:events'
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
6
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
7
+ import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js'
8
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
9
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
10
+ import {
11
+ CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema,
12
+ ListResourceTemplatesRequestSchema, ReadResourceRequestSchema,
13
+ ListPromptsRequestSchema, GetPromptRequestSchema,
14
+ ToolListChangedNotificationSchema, ResourceListChangedNotificationSchema,
15
+ PromptListChangedNotificationSchema,
16
+ } from '@modelcontextprotocol/sdk/types.js'
17
+ import { decodeOAuthConfig } from './oauth-config.js'
18
+ import { readOAuthRecord, writeOAuthRecord } from './oauth-store.js'
19
+
20
+ const interactive = process.env.UPH_MCP_INTERACTIVE === '1'
21
+ const verifying = process.env.UPH_MCP_VERIFY === '1'
22
+ const callbackTimeout = Number(process.env.UPH_OAUTH_CALLBACK_TIMEOUT_MS) || 300000
23
+ const config = decodeOAuthConfig(process.env.UPH_MCP_REMOTE_CONFIG)
24
+ const startedAt = Date.now()
25
+ let activeClient
26
+ let activeTransport
27
+ let callbackServer
28
+ let callbackUrl
29
+ let callbackState
30
+ let callbackResolve
31
+ let callbackReject
32
+ let pendingCallback
33
+
34
+ function emit(event) {
35
+ process.stderr.write(`UPH_OAUTH_EVENT ${JSON.stringify(event)}\n`)
36
+ }
37
+
38
+ function logError(error) {
39
+ process.stderr.write(`${String(error?.message || error).split('\n')[0]}\n`)
40
+ }
41
+
42
+ function closeCallback() {
43
+ callbackServer?.close()
44
+ callbackServer = undefined
45
+ }
46
+
47
+ async function openBrowser(url) {
48
+ if (process.env.UPH_MCP_NO_BROWSER === '1') return
49
+ const target = String(url)
50
+ const child = process.platform === 'win32'
51
+ ? spawn('rundll32.exe', ['url.dll,FileProtocolHandler', target], { detached: true, stdio: 'ignore', windowsHide: true })
52
+ : process.platform === 'darwin'
53
+ ? spawn('open', [target], { detached: true, stdio: 'ignore' })
54
+ : spawn('xdg-open', [target], { detached: true, stdio: 'ignore' })
55
+ child.on('error', () => {})
56
+ child.unref()
57
+ }
58
+
59
+ async function startCallbackListener() {
60
+ if (!interactive) return
61
+ callbackServer = createServer((req, res) => {
62
+ let parsed
63
+ try { parsed = new URL(req.url || '/', 'http://localhost') } catch {
64
+ res.writeHead(400).end()
65
+ return
66
+ }
67
+ if (parsed.pathname !== '/callback') {
68
+ res.writeHead(404).end()
69
+ return
70
+ }
71
+ const code = parsed.searchParams.get('code')
72
+ const state = parsed.searchParams.get('state')
73
+ const error = parsed.searchParams.get('error')
74
+ if (!code || !callbackState || state !== callbackState || error) {
75
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' })
76
+ res.end('OAuth callback could not be validated. Return to DeepSeek Harness and retry.')
77
+ callbackReject?.(new Error(error ? `Authorization failed: ${error}` : 'OAuth callback state is missing or does not match'))
78
+ return
79
+ }
80
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
81
+ res.end('<!doctype html><html><body style="font-family:system-ui;padding:48px"><h2>授权成功</h2><p>可以关闭此页面,返回 DeepSeek Harness。</p></body></html>')
82
+ callbackResolve?.(code)
83
+ })
84
+ callbackServer.on('error', (error) => callbackReject?.(error))
85
+ callbackServer.listen(config.oauth.callbackPort || 0, '127.0.0.1')
86
+ await once(callbackServer, 'listening')
87
+ const address = callbackServer.address()
88
+ callbackUrl = `http://localhost:${address.port}/callback`
89
+ }
90
+
91
+ function waitForCallback() {
92
+ if (!pendingCallback) {
93
+ let timer
94
+ pendingCallback = new Promise((resolve, reject) => {
95
+ callbackResolve = resolve
96
+ callbackReject = reject
97
+ timer = setTimeout(() => reject(new Error('OAuth callback timed out')), callbackTimeout)
98
+ timer.unref?.()
99
+ }).finally(() => { clearTimeout(timer); pendingCallback = undefined })
100
+ }
101
+ return pendingCallback
102
+ }
103
+
104
+ function provider() {
105
+ let record = readOAuthRecord(config.credentialKey)
106
+ const persist = () => writeOAuthRecord(config.credentialKey, record)
107
+ const callback = callbackUrl || record.clientInformation?.redirect_uris?.[0] || `http://localhost:${config.oauth.callbackPort || 0}/callback`
108
+ const custom = config.oauth.mode === 'custom' ? record.customClient : undefined
109
+ return {
110
+ redirectUrl: callback,
111
+ clientMetadata: {
112
+ client_name: 'DeepSeek Harness',
113
+ client_uri: 'https://www.deepseek.com/harness/',
114
+ redirect_uris: [callback],
115
+ grant_types: ['authorization_code', 'refresh_token'],
116
+ response_types: ['code'],
117
+ token_endpoint_auth_method: custom?.client_secret ? 'client_secret_post' : 'none',
118
+ application_type: 'native',
119
+ ...(config.oauth.scope ? { scope: config.oauth.scope } : {}),
120
+ },
121
+ clientInformation() {
122
+ if (config.oauth.mode === 'custom') return custom
123
+ if (interactive && record.clientInformation?.redirect_uris?.length && !record.clientInformation.redirect_uris.includes(callback)) {
124
+ if (record.tokens?.refresh_token) {
125
+ delete record.tokens
126
+ persist()
127
+ }
128
+ return undefined
129
+ }
130
+ return record.clientInformation
131
+ },
132
+ saveClientInformation(info) {
133
+ record.clientInformation = info
134
+ persist()
135
+ },
136
+ tokens() { return record.tokens },
137
+ saveTokens(tokens) {
138
+ record.tokens = tokens
139
+ persist()
140
+ },
141
+ state() {
142
+ callbackState = randomBytes(32).toString('base64url')
143
+ return callbackState
144
+ },
145
+ saveCodeVerifier(verifier) {
146
+ record.codeVerifier = verifier
147
+ persist()
148
+ },
149
+ codeVerifier() {
150
+ if (!record.codeVerifier) throw new Error('OAuth PKCE verifier is missing; please sign in again')
151
+ return record.codeVerifier
152
+ },
153
+ saveDiscoveryState(discovery) {
154
+ record.discovery = discovery
155
+ persist()
156
+ },
157
+ discoveryState() { return record.discovery },
158
+ invalidateCredentials(scope) {
159
+ if (scope === 'all' || scope === 'client') {
160
+ delete record.clientInformation
161
+ delete record.discovery
162
+ }
163
+ if (scope === 'all' || scope === 'tokens') delete record.tokens
164
+ if (scope === 'all' || scope === 'verifier') delete record.codeVerifier
165
+ if (scope === 'discovery') delete record.discovery
166
+ persist()
167
+ },
168
+ async redirectToAuthorization(url) {
169
+ if (!interactive) throw new Error('OAuth 授权已失效,请在连接器设置中重新登录。')
170
+ emit({ status: 'waiting', authorizationUrl: String(url) })
171
+ await openBrowser(url)
172
+ },
173
+ }
174
+ }
175
+
176
+ async function connectRemote() {
177
+ if (!config) throw new Error('Missing remote OAuth configuration')
178
+ await startCallbackListener()
179
+ const oauthProvider = provider()
180
+ const transportOptions = {
181
+ authProvider: oauthProvider,
182
+ requestInit: { headers: config.headers },
183
+ }
184
+ activeClient = new Client({ name: 'universal-plugin-hub', version: '1.0.8' })
185
+ activeTransport = new StreamableHTTPClientTransport(new URL(config.url), transportOptions)
186
+ try {
187
+ await activeClient.connect(activeTransport)
188
+ return activeClient
189
+ } catch (error) {
190
+ if (!interactive || !(error instanceof UnauthorizedError)) throw error
191
+ const code = await waitForCallback()
192
+ await activeClient.close().catch(() => {})
193
+ activeTransport = new StreamableHTTPClientTransport(new URL(config.url), transportOptions)
194
+ await activeTransport.finishAuth(code)
195
+ activeClient = new Client({ name: 'universal-plugin-hub', version: '1.0.8' })
196
+ await activeClient.connect(activeTransport)
197
+ return activeClient
198
+ } finally {
199
+ closeCallback()
200
+ }
201
+ }
202
+
203
+ async function proxyCapabilities(client, server) {
204
+ const capabilities = client.getServerCapabilities() || {}
205
+ if (capabilities.tools) {
206
+ const tools = await client.listTools()
207
+ server.setRequestHandler(ListToolsRequestSchema, (request) => client.listTools(request.params))
208
+ server.setRequestHandler(CallToolRequestSchema, (request) => client.callTool(request.params))
209
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => server.sendToolListChanged())
210
+ }
211
+ if (capabilities.resources) {
212
+ server.setRequestHandler(ListResourcesRequestSchema, (request) => client.listResources(request.params))
213
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) => client.listResourceTemplates(request.params))
214
+ server.setRequestHandler(ReadResourceRequestSchema, (request) => client.readResource(request.params))
215
+ client.setNotificationHandler(ResourceListChangedNotificationSchema, () => server.sendResourceListChanged())
216
+ }
217
+ if (capabilities.prompts) {
218
+ server.setRequestHandler(ListPromptsRequestSchema, (request) => client.listPrompts(request.params))
219
+ server.setRequestHandler(GetPromptRequestSchema, (request) => client.getPrompt(request.params))
220
+ client.setNotificationHandler(PromptListChangedNotificationSchema, () => server.sendPromptListChanged())
221
+ }
222
+ }
223
+
224
+ let shuttingDown = false
225
+ async function shutdown() {
226
+ if (shuttingDown) return
227
+ shuttingDown = true
228
+ closeCallback()
229
+ callbackReject?.(new Error('OAuth authorization was cancelled'))
230
+ await activeClient?.close().catch(() => {})
231
+ process.exit(0)
232
+ }
233
+
234
+ if (!verifying) {
235
+ process.stdin.on('end', shutdown)
236
+ process.stdin.on('close', shutdown)
237
+ }
238
+ process.on('SIGTERM', shutdown)
239
+ process.on('SIGINT', shutdown)
240
+
241
+ try {
242
+ const client = await connectRemote()
243
+ if (verifying) {
244
+ const result = await client.listTools()
245
+ process.stdout.write(JSON.stringify({
246
+ ok: true, status: 200, duration: Date.now() - startedAt,
247
+ message: 'OAuth 授权成功,MCP 连接和工具列表验证通过。',
248
+ tools: result.tools,
249
+ }) + '\n')
250
+ await client.close()
251
+ process.exit(0)
252
+ }
253
+ const server = new Server(
254
+ { name: 'universal-plugin-hub-oauth-bridge', version: '1.0.8' },
255
+ { capabilities: client.getServerCapabilities() || {} },
256
+ )
257
+ await proxyCapabilities(client, server)
258
+ const transport = new StdioServerTransport()
259
+ transport.onclose = () => { void shutdown() }
260
+ await server.connect(transport)
261
+ } catch (error) {
262
+ closeCallback()
263
+ await activeClient?.close().catch(() => {})
264
+ if (verifying) {
265
+ process.stdout.write(JSON.stringify({ ok: false, status: error?.code, message: String(error?.message || error).split('\n')[0] }) + '\n')
266
+ process.exit(0)
267
+ }
268
+ logError(error)
269
+ process.exit(1)
270
+ }
@@ -0,0 +1,48 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ export function isOAuthMode(mode) {
4
+ return mode === 'auto_register' || mode === 'custom'
5
+ }
6
+
7
+ export function oauthCredentialKey(pluginName, connectorName, serverUrl, mode = 'auto_register') {
8
+ return createHash('sha256').update(`${pluginName}::${connectorName}\n${serverUrl}\n${isOAuthMode(mode) ? mode : 'auto_register'}`).digest('hex')
9
+ }
10
+
11
+ export function encodeOAuthConfig(config) {
12
+ return Buffer.from(JSON.stringify(config), 'utf8').toString('base64url')
13
+ }
14
+
15
+ export function decodeOAuthConfig(encoded) {
16
+ if (!encoded) return null
17
+ try {
18
+ const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'))
19
+ return parsed && isOAuthMode(parsed.oauth?.mode) && typeof parsed.url === 'string' ? parsed : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ export function oauthRuntimeConfig(config) {
26
+ return {
27
+ url: config.url,
28
+ headers: Object.fromEntries(Object.entries(config.headers || {}).filter(([key]) => key.toLowerCase() !== 'authorization')),
29
+ oauth: {
30
+ mode: config.oauth.mode,
31
+ clientId: config.oauth.clientId || '',
32
+ callbackPort: config.oauth.callbackPort || null,
33
+ scope: config.oauth.scope || '',
34
+ },
35
+ credentialKey: config.credentialKey,
36
+ }
37
+ }
38
+
39
+ export function remoteConfigFromEntry(config = {}) {
40
+ const remote = decodeOAuthConfig(config.env?.UPH_MCP_REMOTE_CONFIG)
41
+ if (!remote) return null
42
+ return {
43
+ type: 'http', transport: 'http', url: remote.url, headers: remote.headers,
44
+ oauth: remote.oauth.mode, oauthClientId: remote.oauth.clientId,
45
+ oauthCallbackPort: remote.oauth.callbackPort, oauthScope: remote.oauth.scope,
46
+ credentialKey: remote.credentialKey,
47
+ }
48
+ }
@@ -0,0 +1,86 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { execFileSync } from 'node:child_process'
4
+ import { randomBytes } from 'node:crypto'
5
+ import { marketRoot } from './store.js'
6
+
7
+ export function oauthStoreDir() {
8
+ return process.env.UPH_OAUTH_STORE_DIR || join(marketRoot(), 'oauth-credentials')
9
+ }
10
+
11
+ export function oauthCredentialPath(key) {
12
+ if (!/^[a-f0-9]{64}$/.test(key)) throw new Error('Invalid OAuth credential key')
13
+ return join(oauthStoreDir(), `${key}.json`)
14
+ }
15
+
16
+ function protectDpapi(plainText) {
17
+ const script = '$bytes=[Text.Encoding]::UTF8.GetBytes([Console]::In.ReadToEnd()); Add-Type -AssemblyName System.Security; [Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect($bytes,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser))'
18
+ return execFileSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', script], {
19
+ input: plainText, encoding: 'utf8', windowsHide: true, maxBuffer: 4 * 1024 * 1024,
20
+ }).trim()
21
+ }
22
+
23
+ function unprotectDpapi(encoded) {
24
+ const script = '$bytes=[Convert]::FromBase64String([Console]::In.ReadToEnd()); Add-Type -AssemblyName System.Security; [Console]::Out.Write([Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($bytes,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)))'
25
+ return execFileSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', script], {
26
+ input: encoded, encoding: 'utf8', windowsHide: true, maxBuffer: 4 * 1024 * 1024,
27
+ })
28
+ }
29
+
30
+ // Decrypting a DPAPI record spawns a pwsh process (hundreds of ms on Windows),
31
+ // and `installedDetails()` reads one per custom-OAuth connector on every
32
+ // `/state` and plugin-detail request. Cache the plaintext by file content, so a
33
+ // write — which changes the ciphertext — invalidates the entry automatically.
34
+ const RECORD_CACHE = new Map()
35
+
36
+ export function readOAuthRecord(key) {
37
+ const file = oauthCredentialPath(key)
38
+ if (!existsSync(file)) {
39
+ RECORD_CACHE.delete(file)
40
+ return {}
41
+ }
42
+ try {
43
+ const raw = readFileSync(file, 'utf8')
44
+ const cached = RECORD_CACHE.get(file)
45
+ if (cached && cached.raw === raw) return cached.record
46
+ const stored = JSON.parse(raw)
47
+ const record = stored.dpapi === true ? JSON.parse(unprotectDpapi(stored.data)) : stored
48
+ RECORD_CACHE.set(file, { raw, record })
49
+ return record
50
+ } catch {
51
+ return {}
52
+ }
53
+ }
54
+
55
+ export function writeOAuthRecord(key, record) {
56
+ const file = oauthCredentialPath(key)
57
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
58
+ const plainText = JSON.stringify(record)
59
+ const stored = process.platform === 'win32'
60
+ ? { version: 1, dpapi: true, data: protectDpapi(plainText) }
61
+ : JSON.parse(plainText)
62
+ const tmp = join(dirname(file), `.${process.pid}.${randomBytes(8).toString('hex')}.tmp`)
63
+ writeFileSync(tmp, JSON.stringify(stored), { mode: 0o600 })
64
+ renameSync(tmp, file)
65
+ try { if (process.platform !== 'win32') writeFileSync(file, JSON.stringify(stored), { mode: 0o600 }) } catch {}
66
+ // Seed the read cache with what was just written: no pwsh round trip, and a
67
+ // concurrent reader can never see the previous version.
68
+ RECORD_CACHE.set(file, { raw: JSON.stringify(stored), record })
69
+ }
70
+
71
+ export function saveOAuthClientCredentials(key, client) {
72
+ const record = readOAuthRecord(key)
73
+ const sameClient = record.customClient?.client_id === String(client.clientId || '').trim()
74
+ const changedSecret = !!client.clientSecret && client.clientSecret !== record.customClient?.client_secret
75
+ if (!sameClient || changedSecret) {
76
+ delete record.tokens
77
+ delete record.clientInformation
78
+ delete record.discovery
79
+ }
80
+ record.customClient = {
81
+ client_id: String(client.clientId || '').trim(),
82
+ token_endpoint_auth_method: (client.clientSecret || (sameClient && record.customClient?.client_secret)) ? 'client_secret_post' : 'none',
83
+ ...((client.clientSecret || (sameClient && record.customClient?.client_secret)) ? { client_secret: String(client.clientSecret || record.customClient?.client_secret) } : {}),
84
+ }
85
+ writeOAuthRecord(key, record)
86
+ }
package/src/oauth.js ADDED
@@ -0,0 +1,165 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
4
+ import { readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
5
+
6
+ const sessions = new Map()
7
+ const bridgePath = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
8
+ const CALLBACK_TIMEOUT = 5 * 60 * 1000
9
+
10
+ function safeError(error) {
11
+ const raw = String(error?.message || error || 'OAuth connection failed')
12
+ const firstLine = raw.split('\n').find((line) => line.trim()) || raw
13
+ return firstLine.replace(/(access_token|refresh_token|client_secret|code_verifier)[=:]\s*[^\s&]+/gi, '$1=[redacted]').slice(0, 700)
14
+ }
15
+
16
+ export function saveCustomOAuthClient(pluginName, connectorName, payload) {
17
+ if (payload?.oauth !== 'custom' || !payload?.url) return
18
+ if (!String(payload.oauthClientId || '').trim()) throw new Error('使用自有 OAuth 客户端时必须填写 Client ID')
19
+ saveOAuthClientCredentials(oauthCredentialKey(pluginName, connectorName, payload.url, 'custom'), {
20
+ clientId: payload.oauthClientId,
21
+ clientSecret: payload.oauthClientSecret,
22
+ })
23
+ }
24
+
25
+ export function connectorOauthSettings(pluginName, connectorName, payload) {
26
+ return {
27
+ mode: payload.oauth,
28
+ clientId: payload.oauthClientId || '',
29
+ callbackPort: Number(payload.oauthCallbackPort) || null,
30
+ scope: payload.oauthScope || '',
31
+ }
32
+ }
33
+
34
+ function publicSession(session) {
35
+ return {
36
+ found: true, ok: session.status === 'success', pending: session.status === 'waiting' || session.status === 'starting',
37
+ sessionId: session.id, status: session.status, statusCode: session.statusCode,
38
+ message: session.message, authorizationUrl: session.authorizationUrl,
39
+ duration: session.duration, tools: session.tools,
40
+ }
41
+ }
42
+
43
+ function finish(session, result) {
44
+ if (session.done) return
45
+ session.done = true
46
+ clearTimeout(session.timeout)
47
+ try { session.child?.stdin.end() } catch {}
48
+ session.status = result.ok ? 'success' : 'error'
49
+ session.statusCode = result.status
50
+ session.message = result.message
51
+ session.duration = result.duration
52
+ session.tools = result.tools
53
+ try { session.onFinished?.(result) } catch {}
54
+ session.resolve(result)
55
+ setTimeout(() => sessions.delete(session.id), 60000).unref?.()
56
+ }
57
+
58
+ function startProcess(session) {
59
+ let stderrBuffer = ''
60
+ const env = {
61
+ ...process.env,
62
+ UPH_MCP_REMOTE_CONFIG: encodeOAuthConfig(session.config),
63
+ UPH_OAUTH_STORE_DIR: oauthStoreDir(),
64
+ UPH_MCP_INTERACTIVE: '1',
65
+ UPH_MCP_VERIFY: '1',
66
+ ...(session.noBrowser ? { UPH_MCP_NO_BROWSER: '1' } : {}),
67
+ ...(session.callbackTimeout ? { UPH_OAUTH_CALLBACK_TIMEOUT_MS: String(session.callbackTimeout) } : {}),
68
+ }
69
+ const child = spawn(process.execPath, [bridgePath], { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
70
+ session.child = child
71
+ let stdout = ''
72
+ let stderr = ''
73
+ child.stdout.on('data', (chunk) => {
74
+ stdout += chunk
75
+ if (stdout.length > 4 * 1024 * 1024) session.child.kill()
76
+ })
77
+ child.stderr.on('data', (chunk) => {
78
+ stderr = (stderr + chunk).slice(-16000)
79
+ stderrBuffer += chunk
80
+ const lines = stderrBuffer.split('\n')
81
+ stderrBuffer = lines.pop() || ''
82
+ for (const line of lines) {
83
+ if (!line.startsWith('UPH_OAUTH_EVENT ')) continue
84
+ try {
85
+ const event = JSON.parse(line.slice('UPH_OAUTH_EVENT '.length))
86
+ if (session.done) return
87
+ if (event.status === 'waiting') {
88
+ session.status = 'waiting'
89
+ session.authorizationUrl = event.authorizationUrl
90
+ session.message = '请在浏览器中完成授权,完成后会在这里自动继续。'
91
+ }
92
+ } catch {}
93
+ }
94
+ })
95
+ child.on('error', (error) => finish(session, { ok: false, message: safeError(error) }))
96
+ child.on('close', (code) => {
97
+ if (session.cancelled) return finish(session, { ok: false, message: '已取消授权' })
98
+ try {
99
+ const result = JSON.parse(stdout.trim())
100
+ finish(session, result.ok ? result : { ...result, message: safeError(result.message) })
101
+ } catch {
102
+ const diagnostic = stderr.split('\n').filter((line) => line && !line.startsWith('UPH_OAUTH_EVENT ')).slice(-2).join(' ')
103
+ finish(session, { ok: false, message: safeError(diagnostic || `OAuth bridge exited (${code})`) })
104
+ }
105
+ })
106
+ }
107
+
108
+ export function beginOAuthVerification(pluginName, connectorName, payload, options = {}) {
109
+ const credentialKey = oauthCredentialKey(pluginName, connectorName, payload.url, payload.oauth)
110
+ const config = oauthRuntimeConfig({
111
+ url: payload.url, headers: payload.headers,
112
+ oauth: connectorOauthSettings(pluginName, connectorName, payload), credentialKey,
113
+ })
114
+ const previous = [...sessions.values()].find((item) => item.credentialKey === credentialKey && !item.done)
115
+ if (previous) cancelOAuthVerification(previous.id)
116
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`
117
+ let resolve
118
+ const completion = new Promise((r) => { resolve = r })
119
+ const session = {
120
+ id, pluginName, connectorName, credentialKey, config, status: 'starting', startedAt: Date.now(), resolve, completion,
121
+ noBrowser: options.noBrowser || process.env.UPH_MCP_NO_BROWSER === '1', callbackTimeout: options.callbackTimeout, onFinished: options.onFinished,
122
+ timeout: setTimeout(() => cancelOAuthVerification(id, '授权等待超时,请重新测试'), options.callbackTimeout || CALLBACK_TIMEOUT),
123
+ }
124
+ session.timeout.unref?.()
125
+ sessions.set(id, session)
126
+ startProcess(session)
127
+ return session
128
+ }
129
+
130
+ export async function completeOAuthVerification(session) {
131
+ const result = await session.completion
132
+ return { ...result, sessionId: session.id }
133
+ }
134
+
135
+ export function getOAuthVerification(id, owner = {}) {
136
+ const session = id ? sessions.get(id) : [...sessions.values()].find((item) => !item.done && (!owner.pluginName || item.pluginName === owner.pluginName) && (!owner.connectorName || item.connectorName === owner.connectorName))
137
+ const found = !!session && (!owner.pluginName || session.pluginName === owner.pluginName) && (!owner.connectorName || session.connectorName === owner.connectorName)
138
+ return found ? publicSession(session) : { found: false, ok: false, status: 'error', message: '授权会话已结束,请重新测试' }
139
+ }
140
+
141
+ export function cancelOAuthVerification(id, message = '已取消授权', owner = {}) {
142
+ const session = id ? sessions.get(id) : [...sessions.values()].find((item) => !item.done && (!owner.pluginName || item.pluginName === owner.pluginName) && (!owner.connectorName || item.connectorName === owner.connectorName))
143
+ if (!session || session.done) return false
144
+ session.cancelled = true
145
+ try { session.child?.kill() } catch {}
146
+ finish(session, { ok: false, message })
147
+ return true
148
+ }
149
+
150
+ export function cancelAllOAuthVerifications() {
151
+ for (const session of sessions.values()) if (!session.done) cancelOAuthVerification(session.id)
152
+ }
153
+
154
+ export function oauthSessionStatusUrl(pluginName, connectorName, sessionId, userMcp = false) {
155
+ return userMcp
156
+ ? `/mcps/oauth-status?sessionId=${encodeURIComponent(sessionId)}`
157
+ : `/plugins/${encodeURIComponent(pluginName)}/connectors/${encodeURIComponent(connectorName)}/oauth-status?sessionId=${encodeURIComponent(sessionId)}`
158
+ }
159
+
160
+ export function readSavedOAuthClient(pluginName, connectorName, serverUrl, mode = 'custom') {
161
+ const record = readOAuthRecord(oauthCredentialKey(pluginName, connectorName, serverUrl, mode))
162
+ return { clientId: record.customClient?.client_id || '', hasClientSecret: !!record.customClient?.client_secret }
163
+ }
164
+
165
+ export { remoteConfigFromEntry }
package/src/parser.js CHANGED
@@ -856,6 +856,28 @@ export function listHooks(dir) {
856
856
  return hooks
857
857
  }
858
858
 
859
+ /**
860
+ * Collapse every remote transport spelling a manifest may use into the two
861
+ * values the editor and the host understand. Marketplaces write
862
+ * `streamable-http`, `.mcp.json` files write `http`, some older servers write
863
+ * `sse`; a `type` the editor does not recognise would fall back to stdio and
864
+ * show an empty local-command form for a remote URL.
865
+ *
866
+ * This is the single source of truth for that mapping — the host's connector
867
+ * checks and the browser editor call it instead of keeping their own copy of
868
+ * the whitelist, so a new spelling only has to be taught once.
869
+ */
870
+ export function connectorTransport(type, url, command) {
871
+ if (type === 'stdio') return 'stdio'
872
+ if (type === 'http' || type === 'sse' || type === 'streamable-http' || type === 'streamableHttp') return 'http'
873
+ return command && !url ? 'stdio' : 'http'
874
+ }
875
+
876
+ /** True when a transport name is one of the remote spellings. */
877
+ export function isRemoteTransportName(type) {
878
+ return type === 'http' || type === 'sse' || type === 'streamable-http' || type === 'streamableHttp'
879
+ }
880
+
859
881
  /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcp" / "connectors". */
860
882
  export function listConnectors(dir) {
861
883
  const connectors = []
@@ -892,7 +914,7 @@ export function listConnectors(dir) {
892
914
  seen.add(name)
893
915
  connectors.push({
894
916
  name,
895
- type: cfg.type || (cfg.url ? 'http' : 'stdio'),
917
+ type: connectorTransport(cfg.type, cfg.url, cfg.command),
896
918
  url: cfg.url || null,
897
919
  command: cfg.command || null,
898
920
  args: cfg.args || [],
@@ -922,7 +944,7 @@ export function listConnectors(dir) {
922
944
  seen.add(name)
923
945
  connectors.push({
924
946
  name,
925
- type: cfg.type || (cfg.url ? 'http' : 'stdio'),
947
+ type: connectorTransport(cfg.type, cfg.url, cfg.command),
926
948
  url: cfg.url || null,
927
949
  command: cfg.command || null,
928
950
  args: cfg.args || [],
@@ -939,7 +961,7 @@ export function listConnectors(dir) {
939
961
  seen.add(name)
940
962
  connectors.push({
941
963
  name,
942
- type: c.type || (c.url ? 'http' : 'stdio'),
964
+ type: connectorTransport(c.type, c.url, c.command),
943
965
  url: c.url || null,
944
966
  command: c.command || null,
945
967
  args: c.args || [],