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/routes.js CHANGED
@@ -4,26 +4,101 @@
4
4
  * Mutations are same-origin only.
5
5
  */
6
6
  import { existsSync } from 'node:fs'
7
- import { join } from 'node:path'
7
+ import { randomUUID } from 'node:crypto'
8
+ import { join, dirname } from 'node:path'
8
9
  import { sendJson, readJsonBody, sameOrigin } from './http.js'
9
10
  import {
10
- readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir,
11
+ readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir, sourceCacheDir, safeRmDir,
11
12
  } from './store.js'
12
13
  import { ensureSourceCloned, pullSource, safeSegment, materializePlugin } from './market.js'
13
- import { readMarketplace, pluginDetail, pluginContentDir, invalidateMarketplaceCache } from './parser.js'
14
- import { getOrFetchIcon, readLocalIcon } from './icons.js'
14
+ import { readMarketplace, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
15
+ import { getOrFetchIcon, readLocalIconCached, invalidateLocalIconCache } from './icons.js'
15
16
  import {
16
- installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
17
- toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
17
+ installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered, toolCallIconGroups,
18
+ toggleConnector, isConnectorActive, isOAuthConnectorAuthenticated, verifyConnectorAuth, saveConnectorAuth, enableConnector, probeConnectorAuth, probeUserMcpUpdate,
18
19
  fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
20
+ withPluginLock, withSourceLock, removeManagedDirAsync, cancelActivePluginProbes,
19
21
  } from './install.js'
20
- import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, saveUploadedZip } from './local.js'
22
+ import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, saveUploadedZip, saveUploadedStream, MAX_UPLOAD_BYTES } from './local.js'
21
23
  import { uninstallUploadedSkill, uploadedSkillRecord } from './skill-uploads.js'
22
24
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
23
25
  import { remoteConfigFromEntry } from './oauth-config.js'
24
26
  import { scheduledResult } from './runtime.js'
25
27
 
28
+ function scheduledIfOk(result, applyProfile, ids) {
29
+ if (!result || result.ok === false) return result
30
+ return scheduledResult(result, applyProfile, ids)
31
+ }
32
+
26
33
  const API_PREFIX = '/universal-plugin-hub/api'
34
+ const STAGED_UPLOADS = new Map()
35
+ const STAGED_UPLOAD_TTL = 3_600_000
36
+ const STAGED_UPLOAD_LIMIT = 8
37
+
38
+ function sweepStagedUploads() {
39
+ const cutoff = Date.now() - STAGED_UPLOAD_TTL
40
+ for (const [id, entry] of STAGED_UPLOADS) {
41
+ if (entry.createdAt < cutoff) {
42
+ STAGED_UPLOADS.delete(id)
43
+ safeRmDir(entry.uploadDir)
44
+ }
45
+ }
46
+ }
47
+
48
+ function registerStagedUpload(file, uploadDir) {
49
+ sweepStagedUploads()
50
+ while (STAGED_UPLOADS.size >= STAGED_UPLOAD_LIMIT) {
51
+ const oldestKey = STAGED_UPLOADS.keys().next().value
52
+ const oldest = STAGED_UPLOADS.get(oldestKey)
53
+ STAGED_UPLOADS.delete(oldestKey)
54
+ if (oldest?.uploadDir) safeRmDir(oldest.uploadDir)
55
+ }
56
+ const id = randomUUID()
57
+ STAGED_UPLOADS.set(id, { file, uploadDir, createdAt: Date.now() })
58
+ return id
59
+ }
60
+
61
+ function discardStagedUpload(id) {
62
+ const key = String(id || '').trim()
63
+ if (!key) return false
64
+ const entry = STAGED_UPLOADS.get(key)
65
+ if (!entry) return false
66
+ STAGED_UPLOADS.delete(key)
67
+ safeRmDir(entry.uploadDir)
68
+ return true
69
+ }
70
+
71
+ function cleanupAllStagedUploads() {
72
+ for (const [, entry] of STAGED_UPLOADS) {
73
+ if (entry?.uploadDir) safeRmDir(entry.uploadDir)
74
+ }
75
+ STAGED_UPLOADS.clear()
76
+ }
77
+
78
+ function disableUploadTimeouts(req, res) {
79
+ try { req?.setTimeout?.(0) } catch {}
80
+ try { req?.socket?.setTimeout?.(0) } catch {}
81
+ try { res?.setTimeout?.(0) } catch {}
82
+ }
83
+
84
+ async function resolveLocalImportTarget(body) {
85
+ if (body?.uploadId) {
86
+ sweepStagedUploads()
87
+ const id = String(body.uploadId)
88
+ const entry = STAGED_UPLOADS.get(id)
89
+ if (!entry || !existsSync(entry.file)) {
90
+ const error = new Error('上传缓存已过期,请重新选择文件上传')
91
+ error.status = 410
92
+ throw error
93
+ }
94
+ return { target: entry.file, stagedId: id, tempUploadDir: null }
95
+ }
96
+ if (body?.data) {
97
+ const target = await saveUploadedZip(body.data, body.filename)
98
+ return { target, stagedId: null, tempUploadDir: dirname(target) }
99
+ }
100
+ return { target: body?.path, stagedId: null, tempUploadDir: null }
101
+ }
27
102
 
28
103
  export function mountRoutes(webServer, skills = null, applyProfile = null) {
29
104
  const r = webServer.register({
@@ -32,6 +107,7 @@ export function mountRoutes(webServer, skills = null, applyProfile = null) {
32
107
  handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
33
108
  })
34
109
  return () => {
110
+ cleanupAllStagedUploads()
35
111
  try { if (typeof r === 'function') r() } catch {}
36
112
  }
37
113
  }
@@ -40,6 +116,53 @@ function normalizeMcpName(value) {
40
116
  return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
41
117
  }
42
118
 
119
+ const ICON_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox"
120
+
121
+ function etagMatches(ifNoneMatch, etag) {
122
+ if (!ifNoneMatch || !etag) return false
123
+ const raw = Array.isArray(ifNoneMatch) ? ifNoneMatch.join(',') : String(ifNoneMatch)
124
+ const trimmed = raw.trim()
125
+ if (!trimmed) return false
126
+ if (trimmed === '*') return true
127
+ const bare = (tag) => (tag.startsWith('W/') ? tag.slice(2) : tag)
128
+ const target = bare(etag.trim())
129
+ const tokens = trimmed.match(/(?:W\/)?"(?:\\.|[^"])*"|\*/g)
130
+ if (!tokens) return false
131
+ return tokens.some((token) => token === '*' || bare(token) === target)
132
+ }
133
+
134
+ function sendIconResponse(req, res, { buffer, contentType, etag, cacheControl }) {
135
+ const baseHeaders = {
136
+ 'Cache-Control': cacheControl,
137
+ ...(etag ? { 'ETag': etag } : {}),
138
+ 'X-Content-Type-Options': 'nosniff',
139
+ 'Content-Security-Policy': ICON_CSP,
140
+ }
141
+ if (etag && etagMatches(req.headers?.['if-none-match'], etag)) {
142
+ res.writeHead(304, baseHeaders)
143
+ return res.end()
144
+ }
145
+ res.writeHead(200, {
146
+ 'Content-Type': contentType || 'image/png',
147
+ ...baseHeaders,
148
+ })
149
+ return res.end(buffer)
150
+ }
151
+
152
+ /**
153
+ * Resolve one plugin's directory in O(1) without calling readMarketplace()
154
+ * across every sibling plugin and icon in the marketplace.
155
+ */
156
+ function resolvePluginIconDir(sourceId, name) {
157
+ const cleanName = name.toLowerCase()
158
+ const record = readState().plugins.find((p) => p.name.toLowerCase() === cleanName && p.sourceId === sourceId)
159
+ if (record) {
160
+ const inst = installedDir(record.name)
161
+ if (existsSync(inst)) return inst
162
+ }
163
+ return resolveMarketplacePluginDir(sourceId, name)
164
+ }
165
+
43
166
 
44
167
  async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
45
168
  const url = new URL(req.url, 'http://localhost')
@@ -52,14 +175,13 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
52
175
  const targetUrl = url.searchParams.get('u')
53
176
  if (!targetUrl) return sendJson(res, 400, { error: 'missing u parameter' })
54
177
  try {
55
- const { buffer, contentType } = await getOrFetchIcon(targetUrl)
56
- res.writeHead(200, {
57
- 'Content-Type': contentType || 'image/png',
58
- 'Cache-Control': 'public, max-age=604800',
59
- 'X-Content-Type-Options': 'nosniff',
60
- 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox",
178
+ const { buffer, contentType, etag, immutable } = await getOrFetchIcon(targetUrl)
179
+ return sendIconResponse(req, res, {
180
+ buffer,
181
+ contentType,
182
+ etag,
183
+ cacheControl: immutable ? 'public, max-age=31536000, immutable' : 'public, max-age=604800',
61
184
  })
62
- return res.end(buffer)
63
185
  } catch (err) {
64
186
  return sendJson(res, 502, { error: err.message })
65
187
  }
@@ -69,19 +191,25 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
69
191
  try {
70
192
  const sourceId = safeSegment(url.searchParams.get('sourceId'), 'source id')
71
193
  const name = safeSegment(url.searchParams.get('name'), 'plugin name')
72
- const record = readState().plugins.find((p) => p.name === name && p.sourceId === sourceId)
73
- const row = readMarketplace(sourceId).find((p) => p.name === name)
74
- const dir = record && existsSync(installedDir(name)) ? installedDir(name) : (row ? pluginContentDir(sourceId, name, row.source, false) : null)
194
+ const relPath = url.searchParams.get('path')
195
+ const dir = resolvePluginIconDir(sourceId, name)
75
196
  if (!dir) return sendJson(res, 404, { error: 'Plugin icon not found' })
76
- const { buffer, contentType } = readLocalIcon(dir, url.searchParams.get('path'))
77
- res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=604800', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" })
78
- return res.end(buffer)
197
+ const { buffer, contentType, etag, fileVersion } = await readLocalIconCached(dir, relPath, [sourceId, name, relPath])
198
+ const requestedVersion = url.searchParams.get('v')
199
+ const cacheControl = requestedVersion
200
+ ? (requestedVersion === fileVersion ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
201
+ : 'public, max-age=604800'
202
+ return sendIconResponse(req, res, { buffer, contentType, etag, cacheControl })
79
203
  } catch {
80
204
  return sendJson(res, 404, { error: 'Plugin icon not found' })
81
205
  }
82
206
  }
83
207
 
84
208
  // ── state ────────────────────────────────────────────────────────────
209
+ if (method === 'GET' && path === '/tool-call-icons') {
210
+ return sendJson(res, 200, { groups: toolCallIconGroups() })
211
+ }
212
+
85
213
  if (method === 'GET' && path === '/state') {
86
214
  const state = readState()
87
215
  const details = installedDetails()
@@ -147,9 +275,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
147
275
  if (path === '/skills/icon' && method === 'GET' && skills) {
148
276
  try {
149
277
  const item = skills.detail(url.searchParams.get('id'), false)
150
- const { buffer, contentType } = readLocalIcon(item.directory, item.iconPath)
151
- res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=3600', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" })
152
- return res.end(buffer)
278
+ const { buffer, contentType, etag } = await readLocalIconCached(item.directory, item.iconPath, ['skill', item.id, item.iconPath])
279
+ return sendIconResponse(req, res, { buffer, contentType, etag, cacheControl: 'public, max-age=3600' })
153
280
  } catch { return sendJson(res, 404, { error: 'Icon not found' }) }
154
281
  }
155
282
 
@@ -170,16 +297,20 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
170
297
  requireSameOrigin(req)
171
298
  const body = await readJsonBody(req)
172
299
  const sourceId = safeSegment(body.sourceId || 'anthropic', 'source id')
173
- // Clone first if the source has never been fetched (fresh install), so a
174
- // first-launch refresh does not fail with "尚未克隆".
175
- await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
176
- await pullSource(sourceId)
177
- invalidateMarketplaceCache(sourceId)
178
- let plugins = readMarketplace(sourceId)
179
- if (sourceId === 'local') {
180
- const names = new Set(plugins.map(p => p.name))
181
- plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
182
- }
300
+ const plugins = await withSourceLock(sourceId, async () => {
301
+ // Clone first if the source has never been fetched (fresh install), so a
302
+ // first-launch refresh does not fail with "尚未克隆".
303
+ await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
304
+ await pullSource(sourceId)
305
+ invalidateMarketplaceCache(sourceId)
306
+ invalidateLocalIconCache(sourceId)
307
+ let rows = readMarketplace(sourceId)
308
+ if (sourceId === 'local') {
309
+ const names = new Set(rows.map(r => r.name))
310
+ rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
311
+ }
312
+ return rows
313
+ })
183
314
  return sendJson(res, 200, { ok: true, plugins })
184
315
  }
185
316
 
@@ -196,17 +327,18 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
196
327
  const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
197
328
  if (!id) throw new Error('无法从该地址识别仓库')
198
329
 
199
- // Check duplicates BEFORE cloning
200
- const state = readState()
201
- const duplicate = findDuplicateSource(state, id, url)
202
- if (duplicate) {
203
- throw new Error(`该插件源已存在(${duplicate.name})`)
204
- }
205
-
206
- // Validate by cloning into the cache
207
- await ensureSourceCloned(id, url)
208
- const rows = readMarketplace(id)
209
- const count = Array.isArray(rows) ? rows.length : 0
330
+ const count = await withSourceLock(id, async () => {
331
+ // Check duplicates BEFORE cloning
332
+ const state = readState()
333
+ const duplicate = findDuplicateSource(state, id, url)
334
+ if (duplicate) {
335
+ throw new Error(`该插件源已存在(${duplicate.name})`)
336
+ }
337
+ // Validate by cloning into the cache
338
+ await ensureSourceCloned(id, url)
339
+ const rows = readMarketplace(id)
340
+ return Array.isArray(rows) ? rows.length : 0
341
+ })
210
342
 
211
343
  const repoLabel = parsed ? `${parsed.owner}/${parsed.repo}` : (url.replace(/^https?:\/\//i, '').replace(/\.git$/i, ''))
212
344
 
@@ -223,17 +355,66 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
223
355
  // ── local plugin inspection & import ──────────────────────────────────
224
356
  if (method === 'POST' && path === '/plugins/local/inspect') {
225
357
  requireSameOrigin(req)
226
- const body = await readJsonBody(req, 30_000_000)
227
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
228
- const result = await inspectLocalPlugin(target)
229
- return sendJson(res, 200, result)
358
+ disableUploadTimeouts(req, res)
359
+ const contentType = String(req.headers?.['content-type'] || '').toLowerCase()
360
+ let target = ''
361
+ let stagedUpload = null
362
+ if (contentType.includes('application/octet-stream')) {
363
+ const rawHeaderName = String(req.headers?.['x-upload-filename'] || '')
364
+ let filename = url.searchParams.get('filename') || ''
365
+ if (rawHeaderName) {
366
+ try { filename = decodeURIComponent(rawHeaderName) } catch { filename = rawHeaderName }
367
+ }
368
+ stagedUpload = await saveUploadedStream(req, filename, MAX_UPLOAD_BYTES)
369
+ target = stagedUpload.file
370
+ } else {
371
+ const body = await readJsonBody(req, 30_000_000)
372
+ if (body.data) {
373
+ const file = await saveUploadedZip(body.data, body.filename)
374
+ stagedUpload = { file, uploadDir: dirname(file) }
375
+ target = file
376
+ } else {
377
+ target = body.path
378
+ }
379
+ }
380
+ let result
381
+ try {
382
+ result = await inspectLocalPlugin(target)
383
+ } catch (err) {
384
+ if (stagedUpload) safeRmDir(stagedUpload.uploadDir)
385
+ throw err
386
+ }
387
+ // The extraction is only for this preview: clean up the temp extract dir,
388
+ // while staging valid streamed uploads behind an opaque token so confirm does not re-upload.
389
+ if (result.tempExtractDir) safeRmDir(result.tempExtractDir)
390
+ if (!result.ok && stagedUpload) {
391
+ safeRmDir(stagedUpload.uploadDir)
392
+ }
393
+ const uploadId = (result.ok && stagedUpload) ? registerStagedUpload(stagedUpload.file, stagedUpload.uploadDir) : undefined
394
+ const { tempExtractDir, effectiveDir, entries, ...preview } = result
395
+ return sendJson(res, 200, uploadId ? { ...preview, uploadId } : preview)
396
+ }
397
+
398
+ if (method === 'POST' && path === '/plugins/local/upload-cancel') {
399
+ requireSameOrigin(req)
400
+ const body = await readJsonBody(req)
401
+ discardStagedUpload(body?.uploadId)
402
+ return sendJson(res, 200, { ok: true })
230
403
  }
231
404
 
232
405
  if (method === 'POST' && path === '/plugins/local/import') {
233
406
  requireSameOrigin(req)
407
+ disableUploadTimeouts(req, res)
234
408
  const body = await readJsonBody(req, 30_000_000)
235
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
236
- const result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
409
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
410
+ let result
411
+ try {
412
+ result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
413
+ } finally {
414
+ if (tempUploadDir) safeRmDir(tempUploadDir)
415
+ }
416
+ if (stagedId) discardStagedUpload(stagedId)
417
+ invalidateLocalIconCache('local')
237
418
  return sendJson(res, 200, result)
238
419
  }
239
420
 
@@ -241,9 +422,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
241
422
  // junction into $DSH_HOME/skills, then a hot refresh of the Skills tab.
242
423
  if (method === 'POST' && path === '/skills/import') {
243
424
  requireSameOrigin(req)
425
+ disableUploadTimeouts(req, res)
244
426
  const body = await readJsonBody(req, 30_000_000)
245
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
246
- const result = await importLocalSkills(target, { overwrite: body.overwrite === true })
427
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
428
+ let result
429
+ try {
430
+ result = await importLocalSkills(target, {
431
+ overwrite: body.overwrite === true,
432
+ overwriteNames: Array.isArray(body.overwriteNames) ? body.overwriteNames.map(String) : null,
433
+ })
434
+ } finally {
435
+ if (tempUploadDir) safeRmDir(tempUploadDir)
436
+ }
437
+ if (stagedId) discardStagedUpload(stagedId)
247
438
  skills?.refresh()
248
439
  return sendJson(res, 200, result)
249
440
  }
@@ -251,9 +442,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
251
442
  // An uploaded marketplace becomes its own plugin source tab.
252
443
  if (method === 'POST' && path === '/marketplaces/import') {
253
444
  requireSameOrigin(req)
445
+ disableUploadTimeouts(req, res)
254
446
  const body = await readJsonBody(req, 30_000_000)
255
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
256
- const result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true })
447
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
448
+ let result
449
+ try {
450
+ result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true, target: body.target })
451
+ } finally {
452
+ if (tempUploadDir) safeRmDir(tempUploadDir)
453
+ }
454
+ if (stagedId) discardStagedUpload(stagedId)
455
+ if (result?.sourceId) {
456
+ invalidateLocalIconCache(result.sourceId)
457
+ }
257
458
  return sendJson(res, 200, result)
258
459
  }
259
460
 
@@ -271,28 +472,30 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
271
472
  const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
272
473
  if (!id) throw new Error('无法从该地址识别仓库')
273
474
 
274
- const state = readState()
275
- const duplicate = findDuplicateSource(state, id, url)
276
- if (duplicate) {
277
- throw new Error(`该插件源已存在(${duplicate.name})`)
475
+ const validateUnique = (state) => {
476
+ const duplicate = findDuplicateSource(state, id, url)
477
+ if (duplicate) {
478
+ throw new Error(`该插件源已存在(${duplicate.name})`)
479
+ }
480
+ if (state.sources.some((s) => s.name.trim().toLowerCase() === name.toLowerCase())) {
481
+ throw new Error(`已存在同名的插件源「${name}」,请换一个名称`)
482
+ }
278
483
  }
279
484
 
280
- // Check name duplication (e.g. user naming two sources with the same label)
281
- if (state.sources.some((s) => s.name.trim().toLowerCase() === name.toLowerCase())) {
282
- throw new Error(`已存在同名的插件源「${name}」,请换一个名称`)
283
- }
284
-
285
- await ensureSourceCloned(id, url)
286
- const rows = readMarketplace(id)
287
- const count = Array.isArray(rows) ? rows.length : 0
485
+ return sendJson(res, 200, await withSourceLock(id, async () => {
486
+ validateUnique(readState())
487
+ await ensureSourceCloned(id, url)
488
+ const rows = readMarketplace(id)
489
+ const count = Array.isArray(rows) ? rows.length : 0
288
490
 
289
- state.sources.push({ id, name, url, addedAt: Date.now() })
290
- writeState(state)
291
- return sendJson(res, 200, {
292
- ok: true,
293
- source: state.sources[state.sources.length - 1],
294
- pluginCount: count,
295
- })
491
+ // Re-read state after awaiting clone so concurrent mutations (e.g. plugin toggles) are preserved.
492
+ const latestState = readState()
493
+ validateUnique(latestState)
494
+ const source = { id, name, url, addedAt: Date.now() }
495
+ latestState.sources.push(source)
496
+ writeState(latestState)
497
+ return { ok: true, source, pluginCount: count }
498
+ }))
296
499
  }
297
500
 
298
501
  if (method === 'POST' && path === '/sources/reorder') {
@@ -326,15 +529,24 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
326
529
  if (method === 'DELETE' && path.startsWith('/sources/')) {
327
530
  requireSameOrigin(req)
328
531
  const sourceId = safeSegment(path.slice('/sources/'.length), 'source id')
329
- const state = readState()
330
- const source = state.sources.find((s) => s.id === sourceId)
331
- if (!source) throw new Error('插件源不存在')
332
- if (source.builtin) throw new Error('内置源不可删除')
333
- const used = state.plugins.some((p) => p.sourceId === sourceId)
334
- if (used) throw new Error('该源下仍有已安装插件,请先卸载')
335
- state.sources = state.sources.filter((s) => s.id !== sourceId)
336
- writeState(state)
337
- invalidateMarketplaceCache(sourceId)
532
+ await withSourceLock(sourceId, async () => {
533
+ const state = readState()
534
+ const source = state.sources.find((s) => s.id === sourceId)
535
+ if (!source) throw new Error('插件源不存在')
536
+ if (source.builtin) throw new Error('内置源不可删除')
537
+ const used = state.plugins.some((p) => p.sourceId === sourceId)
538
+ if (used) throw new Error('该源下仍有已安装插件,请先卸载')
539
+ // The remote checkout pool is shared by marketplaces. Only remove this
540
+ // source's own clone or uploaded marketplace copy.
541
+ if (sourceId === 'local') cleanupAllStagedUploads()
542
+ if (sourceId !== 'remote') await removeManagedDirAsync(sourceCacheDir(sourceId), { allowTrash: false })
543
+ const latestState = readState()
544
+ latestState.sources = latestState.sources.filter((s) => s.id !== sourceId)
545
+ if (Array.isArray(latestState.tabOrder)) latestState.tabOrder = latestState.tabOrder.filter((id) => id !== sourceId)
546
+ writeState(latestState)
547
+ invalidateMarketplaceCache(sourceId)
548
+ invalidateLocalIconCache(sourceId)
549
+ })
338
550
  return sendJson(res, 200, { ok: true })
339
551
  }
340
552
 
@@ -352,28 +564,33 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
352
564
  }
353
565
  // Migrate legacy patch-only entries (saved before userMcps state existed)
354
566
  let changed = false
567
+ const pluginTools = state.plugins.some(plugin => plugin.name === 'user-mcp') ? readMcpToolsState() : null
355
568
  for (const block of patch) {
356
569
  if (!block || !Array.isArray(block.insert)) continue
357
570
  for (const item of block.insert) {
358
571
  if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
359
572
  const cfg = item.config || {}
573
+ const ownership = pluginTools?.[`user-mcp::${cfg.serverName}`]
574
+ if (ownership?.pluginConnectorOwned || (ownership?.pluginOAuthOwned && remoteConfigFromEntry(cfg))) continue
360
575
  if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
361
576
  state.userMcps.push(userMcpConfig(cfg.serverName, {
362
577
  transport: cfg.transport, url: cfg.url, command: cfg.command,
363
- args: Array.isArray(cfg.args) ? cfg.args : [], env: cfg.env || {},
364
- headers: cfg.headers || {}, oauth: cfg.oauth || 'none',
578
+ args: Array.isArray(cfg.args) ? cfg.args : [], cwd: cfg.cwd,
579
+ env: cfg.env || {}, headers: cfg.headers || {}, oauth: cfg.oauth || 'none',
365
580
  }))
366
581
  changed = true
367
582
  }
368
583
  }
369
584
  }
370
585
  if (changed) writeState(state)
586
+ const toolsState = readMcpToolsState()
371
587
  const mcps = state.userMcps
372
588
  .filter((x) => x && x.name)
373
589
  .map((x) => {
374
590
  const entry = getConnectorEntry('user-mcp', x.name)
375
- const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
591
+ const remote = remoteConfigFromEntry(entry?.config) || toolsState[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
376
592
  const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
593
+ const oauthAuthenticated = isOAuthConnectorAuthenticated('user-mcp', x.name, remote, toolsState)
377
594
  // The live registration says what is *running*; the saved definition
378
595
  // says what the editor should show. The client id comes from the
379
596
  // credential record, since the definition never stores the secret.
@@ -388,7 +605,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
388
605
  // opinion, so a cleared field stays cleared.
389
606
  oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
390
607
  oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
391
- } : {}),
608
+ } : entry?.config?.headers ? { headers: entry.config.headers } : {}),
609
+ oauthAuthenticated,
392
610
  enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
393
611
  }
394
612
  })
@@ -405,7 +623,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
405
623
  if (method === 'POST' && path === '/mcps/verify') {
406
624
  requireSameOrigin(req)
407
625
  const body = await readJsonBody(req)
408
- const name = String(body.name || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
626
+ const name = normalizeMcpName(body.name)
409
627
  const result = await verifyConnectorAuth('user-mcp', name, body)
410
628
  return sendJson(res, 200, result)
411
629
  }
@@ -414,12 +632,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
414
632
  requireSameOrigin(req)
415
633
  const body = await readJsonBody(req)
416
634
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
417
- const result = saveConnectorAuth('user-mcp', name, body)
635
+ const probe = await probeConnectorAuth('user-mcp', name, body)
636
+ if (!probe.ok) return sendJson(res, 200, { ok: false, error: probe.error })
637
+ const result = saveConnectorAuth('user-mcp', name, body, { probe })
418
638
  if (result && result.ok) {
419
639
  const state = readState()
420
640
  if (!Array.isArray(state.userMcps)) state.userMcps = []
421
641
  state.userMcps = state.userMcps.filter((x) => x && x.name !== name)
422
- state.userMcps.push(userMcpConfig(name, body))
642
+ state.userMcps.push(userMcpConfig(name, { ...body, ...probe.definition }))
423
643
  writeState(state)
424
644
  }
425
645
  // A rejected create registered nothing, so there is nothing to apply.
@@ -436,32 +656,47 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
436
656
  ? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
437
657
  : null
438
658
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
439
- const state = readState()
659
+ let state = readState()
440
660
  if (!Array.isArray(state.userMcps)) state.userMcps = []
441
- const idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
661
+ let idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
442
662
  if (idx < 0) throw new Error(`MCP 不存在:${previousName || name}`)
663
+ const oldName = previousName || name
664
+ if (oldName !== name && state.userMcps.some(item => item?.name === name)) {
665
+ throw new Error(`已存在同名 MCP:${name}`)
666
+ }
667
+ const saved = state.userMcps[idx]
668
+ const wasEnabled = !!getConnectorEntry('user-mcp', oldName)
669
+ const enable = wasEnabled || body.enable === true
670
+ const cfg = { ...userMcpConfig(name, body, saved), oauthClientSecret: body.oauthClientSecret }
671
+ let probe
672
+ if (enable) {
673
+ probe = await probeUserMcpUpdate(oldName, name, cfg)
674
+ if (!probe.ok) return sendJson(res, 200, { ok: false, error: probe.error })
675
+ state = readState()
676
+ idx = state.userMcps?.findIndex(x => x?.name === oldName) ?? -1
677
+ if (idx < 0 || JSON.stringify(state.userMcps[idx]) !== JSON.stringify(saved)
678
+ || !!getConnectorEntry('user-mcp', oldName) !== wasEnabled) {
679
+ return sendJson(res, 200, { ok: false, error: 'MCP 配置或开关已变更,请刷新后重试' })
680
+ }
681
+ Object.assign(cfg, probe.definition)
682
+ }
443
683
  if (previousName && previousName !== name) {
444
- // Capture enablement before the rename: a disabled server registers
445
- // nothing, so asking HMR to start its id would target an entry that
446
- // does not exist.
447
- const renamingEnabled = !!getConnectorEntry('user-mcp', previousName)
448
- const renamed = renameUserMcp(previousName, name, body)
684
+ const renamed = renameUserMcp(previousName, name, cfg, { enable, probe })
449
685
  // A rename that failed registered nothing, so there is nothing to apply.
450
686
  if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
451
687
  return sendJson(res, 200, scheduledResult(
452
- renamed, applyProfile, renamingEnabled ? [getConnectorId('user-mcp', name)] : []))
688
+ renamed, applyProfile, enable ? [getConnectorId('user-mcp', name)] : []))
453
689
  }
454
- const wasEnabled = !!getConnectorEntry('user-mcp', name)
455
690
  let result = { ok: true }
456
- if (wasEnabled) {
457
- result = saveConnectorAuth('user-mcp', name, body)
691
+ if (enable) {
692
+ result = saveConnectorAuth('user-mcp', name, cfg, { probe })
458
693
  if (!result || !result.ok) return sendJson(res, 200, result)
459
694
  }
460
695
  // Pass the stored record so an edit keeps the URL history a later delete
461
696
  // needs to find every credential this server ever issued.
462
- state.userMcps[idx] = userMcpConfig(name, body, state.userMcps[idx])
697
+ state.userMcps[idx] = userMcpConfig(name, cfg, state.userMcps[idx])
463
698
  writeState(state)
464
- return sendJson(res, 200, scheduledResult(result, applyProfile, wasEnabled ? [getConnectorId('user-mcp', name)] : []))
699
+ return sendJson(res, 200, enable ? scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]) : result)
465
700
  }
466
701
 
467
702
  // One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
@@ -489,11 +724,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
489
724
  const cfg = (state.userMcps || []).find((x) => x && x.name === name)
490
725
  if (!cfg) throw new Error(`MCP 不存在:${name}`)
491
726
  if (body.enabled !== false) {
492
- const result = saveConnectorAuth('user-mcp', name, cfg)
727
+ const result = await enableConnector('user-mcp', name, cfg, {
728
+ canEnable: () => readState().userMcps?.some(item => item?.name === name && JSON.stringify(item) === JSON.stringify(cfg)),
729
+ })
493
730
  // A rejected enable registered nothing: do not schedule a reconcile.
494
731
  if (!result || !result.ok) return sendJson(res, 200, result)
495
732
  return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
496
733
  }
734
+ const liveHeaders = getConnectorEntry('user-mcp', name)?.config?.headers
735
+ if (liveHeaders) writeState({ ...state, userMcps: state.userMcps.map(item => item === cfg ? { ...cfg, headers: liveHeaders } : item) })
497
736
  unregisterConnector('user-mcp', name)
498
737
  return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
499
738
  }
@@ -553,10 +792,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
553
792
  const pluginName = safeSegment(parts[0], 'plugin name')
554
793
  const connectorName = safeSegment(parts[2], 'connector name')
555
794
  const body = await readJsonBody(req)
556
- const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
557
- // A rejected toggle registered nothing: do not schedule a reconcile.
558
- if (!result || !result.ok) return sendJson(res, 200, result)
559
- return sendJson(res, 200, scheduledResult(result, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
795
+ cancelActivePluginProbes(pluginName, connectorName)
796
+ const outcome = await withPluginLock(pluginName, async () => {
797
+ const pluginRec = readState().plugins.find(plugin => plugin.name === pluginName)
798
+ if (!pluginRec) return { ok: false, error: '插件未安装或已卸载' }
799
+ const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
800
+ if (!canEnable() && body.enabled !== false) return { ok: false, error: '请先启用所属插件' }
801
+ return body.enabled !== false
802
+ ? await enableConnector(pluginName, connectorName, undefined, { pluginOwned: true, canEnable })
803
+ : toggleConnector(pluginName, connectorName, false)
804
+ })
805
+ return sendJson(res, 200, scheduledIfOk(outcome, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
560
806
  }
561
807
 
562
808
  if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
@@ -565,7 +811,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
565
811
  const pluginName = safeSegment(parts[0], 'plugin name')
566
812
  const connectorName = safeSegment(parts[2], 'connector name')
567
813
  const body = await readJsonBody(req)
568
- const result = await verifyConnectorAuth(pluginName, connectorName, body)
814
+ if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
815
+ return sendJson(res, 404, { ok: false, error: '插件未安装或已卸载' })
816
+ }
817
+ const result = await verifyConnectorAuth(pluginName, connectorName, body, { pluginOwned: true })
569
818
  return sendJson(res, 200, result)
570
819
  }
571
820
 
@@ -575,8 +824,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
575
824
  const pluginName = safeSegment(parts[0], 'plugin name')
576
825
  const connectorName = safeSegment(parts[2], 'connector name')
577
826
  const body = await readJsonBody(req)
578
- const result = saveConnectorAuth(pluginName, connectorName, body)
579
- return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
827
+ cancelActivePluginProbes(pluginName, connectorName)
828
+ const outcome = await withPluginLock(pluginName, async () => {
829
+ if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
830
+ return { status: 404, body: { ok: false, error: '插件未安装或已卸载' } }
831
+ }
832
+ const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
833
+ if (!canEnable()) return { status: 200, body: { ok: false, error: '请先启用所属插件' } }
834
+ const result = await enableConnector(pluginName, connectorName, body, { pluginOwned: true, canEnable })
835
+ return { status: 200, body: scheduledIfOk(result, applyProfile, [getConnectorId(pluginName, connectorName)]) }
836
+ })
837
+ return sendJson(res, outcome.status, outcome.body)
580
838
  }
581
839
 
582
840
  // ── plugin detail ────────────────────────────────────────────────────
@@ -595,6 +853,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
595
853
  if (!detail && row?.source && typeof row.source === 'object') {
596
854
  await materializePlugin(sourceId, pluginName, row.source)
597
855
  invalidateMarketplaceCache(sourceId)
856
+ invalidateLocalIconCache(sourceId)
598
857
  row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
599
858
  detail = pluginDetail(sourceId, pluginName, row.source, row)
600
859
  }
@@ -652,14 +911,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
652
911
  pluginName,
653
912
  })
654
913
  invalidateMarketplaceCache(sourceId)
655
- return sendJson(res, 200, scheduledResult(result, applyProfile))
914
+ invalidateLocalIconCache(sourceId)
915
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
656
916
  }
657
917
 
658
918
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
659
919
  requireSameOrigin(req)
660
920
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
661
921
  const body = await readJsonBody(req)
662
- return sendJson(res, 200, scheduledResult(await togglePlugin(pluginName, body.enabled === true), applyProfile))
922
+ return sendJson(res, 200, scheduledIfOk(await togglePlugin(pluginName, body.enabled === true), applyProfile))
663
923
  }
664
924
 
665
925
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
@@ -667,7 +927,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
667
927
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
668
928
  const result = await updatePlugin(pluginName)
669
929
  invalidateMarketplaceCache()
670
- return sendJson(res, 200, scheduledResult(result, applyProfile))
930
+ invalidateLocalIconCache()
931
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
671
932
  }
672
933
 
673
934
  if (method === 'POST' && path === '/restart') {
@@ -708,14 +969,18 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
708
969
  if (method === 'DELETE' && path.startsWith('/plugins/')) {
709
970
  requireSameOrigin(req)
710
971
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
711
- const result = uninstallPlugin(pluginName)
972
+ const result = await uninstallPlugin(pluginName)
712
973
  invalidateMarketplaceCache()
713
- return sendJson(res, 200, scheduledResult(result, applyProfile))
974
+ invalidateLocalIconCache()
975
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
714
976
  }
715
977
 
716
978
  return sendJson(res, 404, { error: 'not found' })
717
979
  } catch (error) {
718
980
  const status = (error && typeof error === 'object' && error.status) ? error.status : 500
981
+ if (status === 413 && res) {
982
+ try { res.setHeader?.('Connection', 'close') } catch {}
983
+ }
719
984
  sendJson(res, status, { error: error instanceof Error ? error.message : String(error) })
720
985
  }
721
986
  }