universal-plugin-hub 1.0.50 → 1.3.1

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/src/market.js CHANGED
@@ -42,9 +42,31 @@ export function pluginPath(root, path) {
42
42
  return dir
43
43
  }
44
44
 
45
+ const SHORTHAND_REPO_RE = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\.git)?$/i
46
+
47
+ /** Normalize remote plugin source objects (Claude `github` / `git-subdir` / `url`). */
48
+ export function normalizeRemotePluginSource(source) {
49
+ if (!source || typeof source !== 'object' || Array.isArray(source)) return source
50
+ if (source.source === 'github') {
51
+ const repo = typeof source.repo === 'string' ? source.repo.trim().replace(/^\/+|\.git$/gi, '') : ''
52
+ const url = typeof source.url === 'string' && source.url.trim()
53
+ ? source.url.trim()
54
+ : (SHORTHAND_REPO_RE.test(repo) ? `https://github.com/${repo}.git` : '')
55
+ return { ...source, ...(url ? { url } : {}) }
56
+ }
57
+ if (source.source === 'git-subdir' && typeof source.url === 'string') {
58
+ const rawUrl = source.url.trim()
59
+ if (SHORTHAND_REPO_RE.test(rawUrl)) {
60
+ return { ...source, url: `https://github.com/${rawUrl.replace(/\.git$/i, '')}.git` }
61
+ }
62
+ }
63
+ return source
64
+ }
65
+
45
66
  /** A marketplace can point back to its own checkout (including a subdirectory). */
46
67
  export function sourceRepositoryDir(cache, source) {
47
- if (!source || !['url', 'git-subdir'].includes(source.source) || typeof source.url !== 'string') return null
68
+ const resolved = normalizeRemotePluginSource(source)
69
+ if (!resolved || !['url', 'git-subdir', 'github'].includes(resolved.source) || typeof resolved.url !== 'string') return null
48
70
  const repoKey = (value) => {
49
71
  try {
50
72
  const url = new URL(value)
@@ -54,15 +76,15 @@ export function sourceRepositoryDir(cache, source) {
54
76
  try {
55
77
  const config = readFileSync(join(cache, '.git', 'config'), 'utf8')
56
78
  const origin = config.match(/\[remote "origin"\]([^\[]*)/)?.[1].match(/^\s*url\s*=\s*(.+)$/m)?.[1].trim()
57
- if (!origin || !repoKey(source.url) || repoKey(origin) !== repoKey(source.url)) return null
79
+ if (!origin || !repoKey(resolved.url) || repoKey(origin) !== repoKey(resolved.url)) return null
58
80
  const head = readFileSync(join(cache, '.git', 'HEAD'), 'utf8').trim()
59
81
  // Reuse only the requested revision; another branch is a different plugin snapshot.
60
- if (source.ref && head !== `ref: refs/heads/${source.ref}` && head !== source.ref) return null
61
- if (source.sha) {
82
+ if (resolved.ref && head !== `ref: refs/heads/${resolved.ref}` && head !== resolved.ref) return null
83
+ if (resolved.sha) {
62
84
  const commit = head.startsWith('ref: ') ? readFileSync(join(cache, '.git', head.slice(5)), 'utf8').trim() : head
63
- if (commit !== source.sha) return null
85
+ if (commit !== resolved.sha) return null
64
86
  }
65
- const dir = source.path ? pluginPath(cache, source.path) : cache
87
+ const dir = resolved.path ? pluginPath(cache, resolved.path) : cache
66
88
  return existsSync(dir) ? dir : null
67
89
  } catch { return null }
68
90
  }
@@ -177,33 +199,42 @@ export async function materializePlugin(sourceId, pluginName, source, { refresh
177
199
  return { dir }
178
200
  }
179
201
 
180
- if (source && typeof source === 'object') {
181
- if (source.source === 'url' || source.source === 'git-subdir') {
182
- if (typeof source.url !== 'string' || !/^https?:\/\//.test(source.url)) {
202
+ const normalized = normalizeRemotePluginSource(source)
203
+ if (normalized && typeof normalized === 'object') {
204
+ if (['url', 'git-subdir', 'github'].includes(normalized.source)) {
205
+ if (typeof normalized.url !== 'string' || !/^https?:\/\//.test(normalized.url)) {
183
206
  throw new Error(`plugin ${pluginName}: unsupported remote url`)
184
207
  }
185
- const remoteKey = slugFromUrl(source.url)
208
+ const remoteKey = slugFromUrl(normalized.url)
186
209
  const checkout = join(sourceCacheDir('remote'), remoteKey)
187
210
  await withGitLock(`remote:${remoteKey}`, async () => {
188
211
  if (!existsSync(join(checkout, '.git'))) {
189
212
  // --depth 1 keeps clones small; `ref` (branch/tag) is honored when
190
- // the marketplace pins one. Exact sha checkout needs a full clone;
191
- // first version installs the pinned ref's head.
213
+ // the marketplace pins one.
192
214
  const args = ['clone', '--depth', '1']
193
- if (source.ref) args.push('--branch', String(source.ref))
194
- args.push(source.url, checkout)
215
+ if (normalized.ref) args.push('--branch', String(normalized.ref))
216
+ args.push(normalized.url, checkout)
195
217
  await runGit(args)
196
218
  } else if (refresh) {
197
219
  // The cached checkout is otherwise reused forever, so updates would
198
220
  // reinstall the first clone's commit. Re-fetch the tracked ref.
199
221
  const args = ['fetch', '--depth', '1', 'origin']
200
- if (source.ref) args.push(String(source.ref))
222
+ if (normalized.ref) args.push(String(normalized.ref))
201
223
  await runGit(args, checkout)
202
224
  await runGit(['reset', '--hard', 'FETCH_HEAD'], checkout)
203
225
  }
226
+ if (normalized.sha && /^[0-9a-f]{7,64}$/i.test(String(normalized.sha))) {
227
+ try {
228
+ const headSha = (await runGit(['rev-parse', 'HEAD'], checkout)).trim()
229
+ if (headSha !== normalized.sha) {
230
+ await runGit(['fetch', '--depth', '1', 'origin', String(normalized.sha)], checkout)
231
+ await runGit(['checkout', '--detach', String(normalized.sha)], checkout)
232
+ }
233
+ } catch {}
234
+ }
204
235
  })
205
- const dir = source.path ? pluginPath(checkout, source.path) : checkout
206
- if (!existsSync(dir)) throw new Error(`plugin ${pluginName}: path ${source.path} not found in remote repo`)
236
+ const dir = normalized.path ? pluginPath(checkout, normalized.path) : checkout
237
+ if (!existsSync(dir)) throw new Error(`plugin ${pluginName}: path ${normalized.path} not found in remote repo`)
207
238
  return { dir }
208
239
  }
209
240
  }
@@ -15,7 +15,7 @@ import {
15
15
  PromptListChangedNotificationSchema,
16
16
  } from '@modelcontextprotocol/sdk/types.js'
17
17
  import { decodeOAuthConfig } from './oauth-config.js'
18
- import { readOAuthRecord, writeOAuthRecord } from './oauth-store.js'
18
+ import { openOAuthRecordWriter, readOAuthRecord } from './oauth-store.js'
19
19
 
20
20
  const interactive = process.env.UPH_MCP_INTERACTIVE === '1'
21
21
  const verifying = process.env.UPH_MCP_VERIFY === '1'
@@ -102,8 +102,13 @@ function waitForCallback() {
102
102
  }
103
103
 
104
104
  function provider() {
105
- let record = readOAuthRecord(config.credentialKey)
106
- const persist = () => writeOAuthRecord(config.credentialKey, record)
105
+ const writer = openOAuthRecordWriter(config.credentialKey)
106
+ if (!writer) throw new Error('OAuth 授权已移除,请重新登录。')
107
+ process.once('exit', () => { try { writer.close() } catch {} })
108
+ const record = readOAuthRecord(config.credentialKey)
109
+ const persist = () => {
110
+ if (!writer.write(record)) throw new Error('OAuth 授权已移除,请重新登录。')
111
+ }
107
112
  const callback = callbackUrl || record.clientInformation?.redirect_uris?.[0] || `http://localhost:${config.oauth.callbackPort || 0}/callback`
108
113
  const custom = config.oauth.mode === 'custom' ? record.customClient : undefined
109
114
  return {
@@ -166,7 +171,7 @@ function provider() {
166
171
  persist()
167
172
  },
168
173
  async redirectToAuthorization(url) {
169
- if (!interactive) throw new Error('OAuth 授权已失效,请在连接器设置中重新登录。')
174
+ if (!interactive) throw new Error('OAuth 授权已失效,请重新登录。')
170
175
  emit({ status: 'waiting', authorizationUrl: String(url) })
171
176
  await openBrowser(url)
172
177
  },
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
2
2
  import { dirname, join } from 'node:path'
3
3
  import { execFileSync } from 'node:child_process'
4
4
  import { randomBytes } from 'node:crypto'
@@ -52,22 +52,62 @@ export function readOAuthRecord(key) {
52
52
  }
53
53
  }
54
54
 
55
- export function writeOAuthRecord(key, record) {
56
- const file = oauthCredentialPath(key)
57
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
55
+ function writeRecord(file, record, stagingDir) {
58
56
  const plainText = JSON.stringify(record)
59
57
  const stored = process.platform === 'win32'
60
58
  ? { version: 1, dpapi: true, data: protectDpapi(plainText) }
61
59
  : 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 {}
60
+ const tmp = join(stagingDir, `.${process.pid}.${randomBytes(8).toString('hex')}.tmp`)
61
+ try {
62
+ writeFileSync(tmp, JSON.stringify(stored), { mode: 0o600 })
63
+ renameSync(tmp, file)
64
+ } finally {
65
+ rmSync(tmp, { force: true })
66
+ }
66
67
  // Seed the read cache with what was just written: no pwsh round trip, and a
67
68
  // concurrent reader can never see the previous version.
68
69
  RECORD_CACHE.set(file, { raw: JSON.stringify(stored), record })
69
70
  }
70
71
 
72
+ export function allowOAuthRecordWrites(key) {
73
+ rmSync(`${oauthCredentialPath(key)}.revoked`, { force: true })
74
+ }
75
+
76
+ export function writeOAuthRecord(key, record) {
77
+ const file = oauthCredentialPath(key)
78
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
79
+ allowOAuthRecordWrites(key)
80
+ writeRecord(file, record, dirname(file))
81
+ }
82
+
83
+ /** A running bridge can publish only while its private staging directory exists. */
84
+ export function openOAuthRecordWriter(key) {
85
+ const file = oauthCredentialPath(key)
86
+ const revoked = `${file}.revoked`
87
+ if (existsSync(revoked)) return null
88
+ const root = `${file}.writers`
89
+ mkdirSync(root, { recursive: true, mode: 0o700 })
90
+ const directory = mkdtempSync(join(root, 'bridge-'))
91
+ const close = () => rmSync(directory, { recursive: true, force: true })
92
+ if (existsSync(revoked)) {
93
+ close()
94
+ return null
95
+ }
96
+ return {
97
+ write(record) {
98
+ if (!existsSync(directory) || existsSync(revoked)) return false
99
+ try {
100
+ writeRecord(file, record, directory)
101
+ return true
102
+ } catch (error) {
103
+ if (error.code === 'ENOENT' && !existsSync(directory)) return false
104
+ throw error
105
+ }
106
+ },
107
+ close,
108
+ }
109
+ }
110
+
71
111
  export function saveOAuthClientCredentials(key, client) {
72
112
  const record = readOAuthRecord(key)
73
113
  const sameClient = record.customClient?.client_id === String(client.clientId || '').trim()
@@ -90,8 +130,18 @@ export function saveOAuthClientCredentials(key, client) {
90
130
  * removed: leaving the file behind would resurrect a stale sign-in if a server
91
131
  * of the same name were added again with the same URL and OAuth mode.
92
132
  */
93
- export function deleteOAuthRecord(key) {
133
+ export function deleteOAuthRecord(key, { required = false, ifPresent = false } = {}) {
94
134
  const file = oauthCredentialPath(key)
95
135
  RECORD_CACHE.delete(file)
96
- try { rmSync(file, { force: true }) } catch {}
136
+ try {
137
+ if (ifPresent && !existsSync(file) && !existsSync(`${file}.writers`)) return
138
+ // Block new bridges first. Removing the old bridges' staging directories
139
+ // prevents even a refresh already in progress from publishing after cleanup.
140
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
141
+ writeFileSync(`${file}.revoked`, '', { mode: 0o600 })
142
+ rmSync(`${file}.writers`, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
143
+ rmSync(file, { force: true })
144
+ } catch (error) {
145
+ if (required) throw error
146
+ }
97
147
  }
package/src/oauth.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { fileURLToPath } from 'node:url'
3
3
  import { encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
4
- import { readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
4
+ import { allowOAuthRecordWrites, readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
5
5
 
6
6
  const sessions = new Map()
7
7
  const bridgePath = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
@@ -34,9 +34,10 @@ export function connectorOauthSettings(pluginName, connectorName, payload) {
34
34
  function publicSession(session) {
35
35
  return {
36
36
  found: true, ok: session.status === 'success', pending: session.status === 'waiting' || session.status === 'starting',
37
- sessionId: session.id, status: session.status, statusCode: session.statusCode,
37
+ sessionId: session.id, server: session.connectorName, status: session.status, statusCode: session.statusCode,
38
38
  message: session.message, authorizationUrl: session.authorizationUrl,
39
39
  duration: session.duration, tools: session.tools,
40
+ ...(Array.isArray(session.tools) ? { toolsCount: session.tools.length } : {}),
40
41
  }
41
42
  }
42
43
 
@@ -107,6 +108,7 @@ function startProcess(session) {
107
108
 
108
109
  export function beginOAuthVerification(pluginName, connectorName, payload, options = {}) {
109
110
  const credentialKey = oauthCredentialKey(pluginName, connectorName, payload.url, payload.oauth)
111
+ allowOAuthRecordWrites(credentialKey)
110
112
  const config = oauthRuntimeConfig({
111
113
  url: payload.url, headers: payload.headers,
112
114
  oauth: connectorOauthSettings(pluginName, connectorName, payload), credentialKey,
@@ -117,7 +119,8 @@ export function beginOAuthVerification(pluginName, connectorName, payload, optio
117
119
  let resolve
118
120
  const completion = new Promise((r) => { resolve = r })
119
121
  const session = {
120
- id, pluginName, connectorName, credentialKey, config, status: 'starting', startedAt: Date.now(), resolve, completion,
122
+ id, pluginName, connectorName, credentialKey, config, pluginOwned: options.pluginOwned,
123
+ status: 'starting', startedAt: Date.now(), resolve, completion,
121
124
  noBrowser: options.noBrowser || process.env.UPH_MCP_NO_BROWSER === '1', callbackTimeout: options.callbackTimeout, onFinished: options.onFinished,
122
125
  timeout: setTimeout(() => cancelOAuthVerification(id, '授权等待超时,请重新测试'), options.callbackTimeout || CALLBACK_TIMEOUT),
123
126
  }
@@ -151,6 +154,30 @@ export function cancelAllOAuthVerifications() {
151
154
  for (const session of sessions.values()) if (!session.done) cancelOAuthVerification(session.id)
152
155
  }
153
156
 
157
+ /** Stop pending verification for a plugin before removing its credentials. */
158
+ export function cancelPluginOAuthVerifications(pluginName, ownsConnector = () => true) {
159
+ const pending = []
160
+ for (const session of sessions.values()) {
161
+ if (session.pluginName !== pluginName) continue
162
+ if (pluginName === 'user-mcp' && (!session.pluginOwned || !ownsConnector(session.connectorName))) continue
163
+ session.cancelled = true
164
+ const child = session.child
165
+ if (child?.pid && child.exitCode === null && child.signalCode === null) {
166
+ pending.push(new Promise(resolve => child.once('close', resolve)))
167
+ // Do not leave the callback or a token exchange running during cleanup.
168
+ child.kill('SIGKILL')
169
+ }
170
+ finish(session, { ok: false, message: '插件已卸载,授权已取消' })
171
+ }
172
+ return pending.length ? Promise.all(pending) : null
173
+ }
174
+
175
+ export function standaloneOAuthConnectorNames() {
176
+ return [...sessions.values()]
177
+ .filter(session => session.pluginName === 'user-mcp' && !session.pluginOwned)
178
+ .map(session => session.connectorName)
179
+ }
180
+
154
181
  export function oauthSessionStatusUrl(pluginName, connectorName, sessionId, userMcp = false) {
155
182
  return userMcp
156
183
  ? `/mcps/oauth-status?sessionId=${encodeURIComponent(sessionId)}`