universal-plugin-hub 1.1.0 → 1.5.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/src/market.js CHANGED
@@ -5,10 +5,11 @@
5
5
  * is derived from a slug validated with `safeSegment`. Errors carry a
6
6
  * user-facing message; network/git failures are retryable at the UI level.
7
7
  */
8
+ import { createHash } from 'node:crypto'
8
9
  import { execFile } from 'node:child_process'
9
- import { existsSync, mkdirSync, readFileSync } from 'node:fs'
10
- import { join, resolve, relative, isAbsolute } from 'node:path'
11
- import { sourceCacheDir, safeRmDir, readState } from './store.js'
10
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
+ import { dirname, join, resolve, relative, isAbsolute } from 'node:path'
12
+ import { sourceCacheDir, removeManagedDir, safeRmDir, readState } from './store.js'
12
13
 
13
14
  const SEGMENT_RE = /^[a-z0-9][a-z0-9._-]*$/i
14
15
 
@@ -42,9 +43,42 @@ export function pluginPath(root, path) {
42
43
  return dir
43
44
  }
44
45
 
46
+ const SHORTHAND_REPO_RE = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\.git)?$/i
47
+
48
+ /** Normalize remote plugin source objects (Claude `github` / `git-subdir` / `url`). */
49
+ export function normalizeRemotePluginSource(source) {
50
+ if (!source || typeof source !== 'object' || Array.isArray(source)) return source
51
+ if (source.source === 'github') {
52
+ const repo = typeof source.repo === 'string' ? source.repo.trim().replace(/^\/+|\.git$/gi, '') : ''
53
+ let url = ''
54
+ if (typeof source.url === 'string' && source.url.trim()) url = source.url.trim()
55
+ else if (SHORTHAND_REPO_RE.test(repo)) url = `https://github.com/${repo}.git`
56
+ return { ...source, ...(url ? { url } : {}) }
57
+ }
58
+ if (source.source === 'git-subdir' && typeof source.url === 'string') {
59
+ const rawUrl = source.url.trim()
60
+ if (SHORTHAND_REPO_RE.test(rawUrl)) {
61
+ return { ...source, url: `https://github.com/${rawUrl.replace(/\.git$/i, '')}.git` }
62
+ }
63
+ }
64
+ return source
65
+ }
66
+
67
+ function readCheckoutOrigin(dir) {
68
+ try {
69
+ const config = readFileSync(join(dir, '.git', 'config'), 'utf8')
70
+ return config.match(/(?:^|\r?\n)\[remote "origin"\][^\n]*\r?\n([\s\S]*?)(?=\r?\n\[|$)/)?.[1]
71
+ .match(/^\s*url\s*=\s*(.+)$/m)?.[1].trim()
72
+ } catch (error) {
73
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error
74
+ return undefined
75
+ }
76
+ }
77
+
45
78
  /** A marketplace can point back to its own checkout (including a subdirectory). */
46
79
  export function sourceRepositoryDir(cache, source) {
47
- if (!source || !['url', 'git-subdir'].includes(source.source) || typeof source.url !== 'string') return null
80
+ const resolved = normalizeRemotePluginSource(source)
81
+ if (!resolved || !['url', 'git-subdir', 'github'].includes(resolved.source) || typeof resolved.url !== 'string') return null
48
82
  const repoKey = (value) => {
49
83
  try {
50
84
  const url = new URL(value)
@@ -52,17 +86,16 @@ export function sourceRepositoryDir(cache, source) {
52
86
  } catch { return null }
53
87
  }
54
88
  try {
55
- const config = readFileSync(join(cache, '.git', 'config'), 'utf8')
56
- 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
89
+ const origin = readCheckoutOrigin(cache)
90
+ if (!origin || !repoKey(resolved.url) || repoKey(origin) !== repoKey(resolved.url)) return null
58
91
  const head = readFileSync(join(cache, '.git', 'HEAD'), 'utf8').trim()
59
92
  // 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) {
93
+ if (resolved.ref && head !== `ref: refs/heads/${resolved.ref}` && head !== resolved.ref) return null
94
+ if (resolved.sha) {
62
95
  const commit = head.startsWith('ref: ') ? readFileSync(join(cache, '.git', head.slice(5)), 'utf8').trim() : head
63
- if (commit !== source.sha) return null
96
+ if (commit !== resolved.sha) return null
64
97
  }
65
- const dir = source.path ? pluginPath(cache, source.path) : cache
98
+ const dir = resolved.path ? pluginPath(cache, resolved.path) : cache
66
99
  return existsSync(dir) ? dir : null
67
100
  } catch { return null }
68
101
  }
@@ -83,11 +116,11 @@ function formatGitError(stderr, errorMsg) {
83
116
  return last.length > 50 ? last.slice(0, 48) + '…' : last
84
117
  }
85
118
 
86
- function runGit(args, cwd) {
119
+ function runGit(args, cwd, timeout) {
87
120
  return new Promise((resolve, reject) => {
88
- execFile('git', args, { cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
121
+ execFile('git', args, { cwd, timeout, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
89
122
  if (error) {
90
- const detail = formatGitError(stderr, error.message)
123
+ const detail = error.killed && timeout ? 'Git 操作超时,请检查网络后重试' : formatGitError(stderr, error.message)
91
124
  reject(new Error(detail))
92
125
  return
93
126
  }
@@ -96,41 +129,61 @@ function runGit(args, cwd) {
96
129
  })
97
130
  }
98
131
 
132
+ function hasSourceCheckout(dir) {
133
+ const git = join(dir, '.git')
134
+ // Legacy clones wrote their first index after checking out the worktree.
135
+ return existsSync(join(git, 'uph-clone-complete')) || existsSync(join(git, 'index'))
136
+ }
137
+
138
+ async function cloneRepoToCache(dir, url, { branch, timeoutMs } = {}) {
139
+ const hadCheckout = hasSourceCheckout(dir)
140
+ if (hadCheckout && readCheckoutOrigin(dir) === url) return false
141
+
142
+ if (!hadCheckout) removeManagedDir(dir, { allowTrash: true })
143
+ const parent = dirname(dir)
144
+ mkdirSync(parent, { recursive: true })
145
+ const staging = mkdtempSync(join(parent, '.clone-'))
146
+ try {
147
+ const args = ['clone', '--depth', '1']
148
+ if (branch) args.push('--branch', String(branch))
149
+ args.push(url, staging)
150
+ await runGit(args, undefined, timeoutMs)
151
+ // Empty repositories can be cloned successfully without an index.
152
+ writeFileSync(join(staging, '.git', 'uph-clone-complete'), '')
153
+ // The slug can collide with an abandoned preview from another repository.
154
+ // Keep that checkout until the requested clone has completed successfully.
155
+ if (hadCheckout) removeManagedDir(dir, { deferCleanup: true })
156
+ renameSync(staging, dir)
157
+ return true
158
+ } finally {
159
+ safeRmDir(staging)
160
+ }
161
+ }
162
+
163
+ /** Derive a collision-free cache key for a remote plugin repository checkout. */
164
+ export function remoteCheckoutKey(url, ref = '') {
165
+ const identity = ref ? `${url}\0${ref}` : String(url)
166
+ const digest = createHash('sha256').update(identity).digest('hex').slice(0, 8)
167
+ return `${slugFromUrl(url)}-${digest}`
168
+ }
169
+
170
+ /** Resolve the cache directory for a materialized remote plugin repository. */
171
+ export function remoteCheckoutDir(url, ref = '') {
172
+ return join(sourceCacheDir('remote'), remoteCheckoutKey(url, ref))
173
+ }
174
+
99
175
  /** Clone a source repository into its cache dir (idempotent, concurrency-safe). */
100
- export async function ensureSourceCloned(sourceId, url) {
176
+ export async function ensureSourceCloned(sourceId, url, { onCloned } = {}) {
101
177
  safeSegment(sourceId, 'source id')
102
178
  const dir = sourceCacheDir(sourceId)
103
179
  if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(url || ''))) {
104
180
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
105
181
  return dir
106
182
  }
107
- if (existsSync(join(dir, '.git'))) return dir
183
+ if (hasSourceCheckout(dir) && readCheckoutOrigin(dir) === url) return dir
108
184
 
109
185
  return withGitLock(`src:${sourceId}`, async () => {
110
- // Another request may have completed the clone while we waited on the lock.
111
- if (existsSync(join(dir, '.git'))) return dir
112
-
113
- // Clean incomplete cache if previous clone failed
114
- if (existsSync(dir)) {
115
- try {
116
- safeRmDir(dir)
117
- } catch {
118
- // ignore rm error
119
- }
120
- }
121
-
122
- try {
123
- await runGit(['clone', '--depth', '1', url, dir])
124
- } catch (err) {
125
- if (existsSync(dir) && !existsSync(join(dir, '.git'))) {
126
- try {
127
- safeRmDir(dir)
128
- } catch {
129
- // ignore rm error
130
- }
131
- }
132
- throw err
133
- }
186
+ if (await cloneRepoToCache(dir, url, { timeoutMs: 120_000 })) onCloned?.()
134
187
  return dir
135
188
  })
136
189
  }
@@ -177,33 +230,36 @@ export async function materializePlugin(sourceId, pluginName, source, { refresh
177
230
  return { dir }
178
231
  }
179
232
 
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)) {
233
+ const normalized = normalizeRemotePluginSource(source)
234
+ if (normalized && typeof normalized === 'object') {
235
+ if (['url', 'git-subdir', 'github'].includes(normalized.source)) {
236
+ if (typeof normalized.url !== 'string' || !/^https?:\/\//.test(normalized.url)) {
183
237
  throw new Error(`plugin ${pluginName}: unsupported remote url`)
184
238
  }
185
- const remoteKey = slugFromUrl(source.url)
239
+ const remoteKey = remoteCheckoutKey(normalized.url, normalized.ref)
186
240
  const checkout = join(sourceCacheDir('remote'), remoteKey)
187
241
  await withGitLock(`remote:${remoteKey}`, async () => {
188
- if (!existsSync(join(checkout, '.git'))) {
189
- // --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.
192
- const args = ['clone', '--depth', '1']
193
- if (source.ref) args.push('--branch', String(source.ref))
194
- args.push(source.url, checkout)
195
- await runGit(args)
196
- } else if (refresh) {
242
+ const cloned = await cloneRepoToCache(checkout, normalized.url, { branch: normalized.ref })
243
+ if (!cloned && refresh) {
197
244
  // The cached checkout is otherwise reused forever, so updates would
198
245
  // reinstall the first clone's commit. Re-fetch the tracked ref.
199
246
  const args = ['fetch', '--depth', '1', 'origin']
200
- if (source.ref) args.push(String(source.ref))
247
+ if (normalized.ref) args.push(String(normalized.ref))
201
248
  await runGit(args, checkout)
202
249
  await runGit(['reset', '--hard', 'FETCH_HEAD'], checkout)
203
250
  }
251
+ if (normalized.sha && /^[0-9a-f]{7,64}$/i.test(String(normalized.sha))) {
252
+ try {
253
+ const headSha = (await runGit(['rev-parse', 'HEAD'], checkout)).trim()
254
+ if (headSha !== normalized.sha) {
255
+ await runGit(['fetch', '--depth', '1', 'origin', String(normalized.sha)], checkout)
256
+ await runGit(['checkout', '--detach', String(normalized.sha)], checkout)
257
+ }
258
+ } catch {}
259
+ }
204
260
  })
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`)
261
+ const dir = normalized.path ? pluginPath(checkout, normalized.path) : checkout
262
+ if (!existsSync(dir)) throw new Error(`plugin ${pluginName}: path ${normalized.path} not found in remote repo`)
207
263
  return { dir }
208
264
  }
209
265
  }
@@ -171,7 +171,7 @@ function provider() {
171
171
  persist()
172
172
  },
173
173
  async redirectToAuthorization(url) {
174
- if (!interactive) throw new Error('OAuth 授权已失效,请在连接器设置中重新登录。')
174
+ if (!interactive) throw new Error('OAuth 授权已失效,请重新登录。')
175
175
  emit({ status: 'waiting', authorizationUrl: String(url) })
176
176
  await openBrowser(url)
177
177
  },
@@ -208,7 +208,6 @@ async function connectRemote() {
208
208
  async function proxyCapabilities(client, server) {
209
209
  const capabilities = client.getServerCapabilities() || {}
210
210
  if (capabilities.tools) {
211
- const tools = await client.listTools()
212
211
  server.setRequestHandler(ListToolsRequestSchema, (request) => client.listTools(request.params))
213
212
  server.setRequestHandler(CallToolRequestSchema, (request) => client.callTool(request.params))
214
213
  client.setNotificationHandler(ToolListChangedNotificationSchema, () => server.sendToolListChanged())
@@ -36,6 +36,10 @@ export function oauthRuntimeConfig(config) {
36
36
  }
37
37
  }
38
38
 
39
+ export function bridgeRuntimeEnv(env = {}, versions = process.versions) {
40
+ return versions?.electron ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : { ...env }
41
+ }
42
+
39
43
  export function remoteConfigFromEntry(config = {}) {
40
44
  const remote = decodeOAuthConfig(config.env?.UPH_MCP_REMOTE_CONFIG)
41
45
  if (!remote) return null
@@ -108,20 +108,37 @@ export function openOAuthRecordWriter(key) {
108
108
  }
109
109
  }
110
110
 
111
+ /**
112
+ * Block new bridges and remove existing staging directories so a concurrent or
113
+ * stale writer cannot republish superseded credentials.
114
+ */
115
+ function revokeOAuthWriters(file) {
116
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
117
+ writeFileSync(`${file}.revoked`, '', { mode: 0o600 })
118
+ rmSync(`${file}.writers`, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
119
+ }
120
+
111
121
  export function saveOAuthClientCredentials(key, client) {
112
- const record = readOAuthRecord(key)
113
- const sameClient = record.customClient?.client_id === String(client.clientId || '').trim()
122
+ const record = { ...readOAuthRecord(key) }
123
+ const nextClientId = String(client.clientId || '').trim()
124
+ const sameClient = record.customClient?.client_id === nextClientId
114
125
  const changedSecret = !!client.clientSecret && client.clientSecret !== record.customClient?.client_secret
115
126
  if (!sameClient || changedSecret) {
116
127
  delete record.tokens
117
128
  delete record.clientInformation
118
129
  delete record.discovery
119
130
  }
120
- record.customClient = {
121
- client_id: String(client.clientId || '').trim(),
122
- token_endpoint_auth_method: (client.clientSecret || (sameClient && record.customClient?.client_secret)) ? 'client_secret_post' : 'none',
123
- ...((client.clientSecret || (sameClient && record.customClient?.client_secret)) ? { client_secret: String(client.clientSecret || record.customClient?.client_secret) } : {}),
131
+ const nextSecret = client.clientSecret || (sameClient ? record.customClient?.client_secret : '')
132
+ const nextCustomClient = {
133
+ client_id: nextClientId,
134
+ token_endpoint_auth_method: nextSecret ? 'client_secret_post' : 'none',
135
+ ...(nextSecret ? { client_secret: String(nextSecret) } : {}),
136
+ }
137
+ if (sameClient && !changedSecret && JSON.stringify(record.customClient) === JSON.stringify(nextCustomClient)) {
138
+ return
124
139
  }
140
+ if (!sameClient || changedSecret) revokeOAuthWriters(oauthCredentialPath(key))
141
+ record.customClient = nextCustomClient
125
142
  writeOAuthRecord(key, record)
126
143
  }
127
144
 
@@ -135,11 +152,7 @@ export function deleteOAuthRecord(key, { required = false, ifPresent = false } =
135
152
  RECORD_CACHE.delete(file)
136
153
  try {
137
154
  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 })
155
+ revokeOAuthWriters(file)
143
156
  rmSync(file, { force: true })
144
157
  } catch (error) {
145
158
  if (required) throw error
package/src/oauth.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { fileURLToPath } from 'node:url'
3
- import { encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
3
+ import { bridgeRuntimeEnv, encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
4
4
  import { allowOAuthRecordWrites, readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
5
5
 
6
6
  const sessions = new Map()
@@ -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
 
@@ -57,7 +58,7 @@ function finish(session, result) {
57
58
 
58
59
  function startProcess(session) {
59
60
  let stderrBuffer = ''
60
- const env = {
61
+ const env = bridgeRuntimeEnv({
61
62
  ...process.env,
62
63
  UPH_MCP_REMOTE_CONFIG: encodeOAuthConfig(session.config),
63
64
  UPH_OAUTH_STORE_DIR: oauthStoreDir(),
@@ -65,7 +66,7 @@ function startProcess(session) {
65
66
  UPH_MCP_VERIFY: '1',
66
67
  ...(session.noBrowser ? { UPH_MCP_NO_BROWSER: '1' } : {}),
67
68
  ...(session.callbackTimeout ? { UPH_OAUTH_CALLBACK_TIMEOUT_MS: String(session.callbackTimeout) } : {}),
68
- }
69
+ })
69
70
  const child = spawn(process.execPath, [bridgePath], { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
70
71
  session.child = child
71
72
  let stdout = ''