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/routes.js CHANGED
@@ -4,26 +4,106 @@
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, removeManagedDir, sourceCacheDir,
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, readMarketplaceName, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
15
+ import { getOrFetchIcon, readLocalIconCached, invalidateLocalIconCache } from './icons.js'
15
16
  import {
16
- installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered, toolCallIconGroups,
17
- toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
17
+ installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, installedPluginDetail, 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'
27
+ import { listAtPlugins, invalidateAtPluginsCache } from './at-plugins.js'
28
+
29
+ function scheduledIfOk(result, applyProfile, ids) {
30
+ if (!result || result.ok === false) return result
31
+ return scheduledResult(result, applyProfile, ids)
32
+ }
33
+
34
+ function withPluginDetail(outcome, pluginName) {
35
+ return outcome && outcome.ok !== false ? { ...outcome, plugin: installedPluginDetail(pluginName) } : outcome
36
+ }
25
37
 
26
38
  const API_PREFIX = '/universal-plugin-hub/api'
39
+ const STAGED_UPLOADS = new Map()
40
+ const STAGED_UPLOAD_TTL = 3_600_000
41
+ const STAGED_UPLOAD_LIMIT = 8
42
+
43
+ function sweepStagedUploads() {
44
+ const cutoff = Date.now() - STAGED_UPLOAD_TTL
45
+ for (const [id, entry] of STAGED_UPLOADS) {
46
+ if (entry.createdAt < cutoff) {
47
+ STAGED_UPLOADS.delete(id)
48
+ safeRmDir(entry.uploadDir)
49
+ }
50
+ }
51
+ }
52
+
53
+ function registerStagedUpload(file, uploadDir) {
54
+ sweepStagedUploads()
55
+ while (STAGED_UPLOADS.size >= STAGED_UPLOAD_LIMIT) {
56
+ const oldestKey = STAGED_UPLOADS.keys().next().value
57
+ const oldest = STAGED_UPLOADS.get(oldestKey)
58
+ STAGED_UPLOADS.delete(oldestKey)
59
+ if (oldest?.uploadDir) safeRmDir(oldest.uploadDir)
60
+ }
61
+ const id = randomUUID()
62
+ STAGED_UPLOADS.set(id, { file, uploadDir, createdAt: Date.now() })
63
+ return id
64
+ }
65
+
66
+ function discardStagedUpload(id) {
67
+ const key = String(id || '').trim()
68
+ if (!key) return false
69
+ const entry = STAGED_UPLOADS.get(key)
70
+ if (!entry) return false
71
+ STAGED_UPLOADS.delete(key)
72
+ safeRmDir(entry.uploadDir)
73
+ return true
74
+ }
75
+
76
+ function cleanupAllStagedUploads() {
77
+ for (const [, entry] of STAGED_UPLOADS) {
78
+ if (entry?.uploadDir) safeRmDir(entry.uploadDir)
79
+ }
80
+ STAGED_UPLOADS.clear()
81
+ }
82
+
83
+ function disableUploadTimeouts(req, res) {
84
+ try { req?.setTimeout?.(0) } catch {}
85
+ try { req?.socket?.setTimeout?.(0) } catch {}
86
+ try { res?.setTimeout?.(0) } catch {}
87
+ }
88
+
89
+ async function resolveLocalImportTarget(body) {
90
+ if (body?.uploadId) {
91
+ sweepStagedUploads()
92
+ const id = String(body.uploadId)
93
+ const entry = STAGED_UPLOADS.get(id)
94
+ if (!entry || !existsSync(entry.file)) {
95
+ const error = new Error('上传缓存已过期,请重新选择文件上传')
96
+ error.status = 410
97
+ throw error
98
+ }
99
+ return { target: entry.file, stagedId: id, tempUploadDir: null }
100
+ }
101
+ if (body?.data) {
102
+ const target = await saveUploadedZip(body.data, body.filename)
103
+ return { target, stagedId: null, tempUploadDir: dirname(target) }
104
+ }
105
+ return { target: body?.path, stagedId: null, tempUploadDir: null }
106
+ }
27
107
 
28
108
  export function mountRoutes(webServer, skills = null, applyProfile = null) {
29
109
  const r = webServer.register({
@@ -32,6 +112,7 @@ export function mountRoutes(webServer, skills = null, applyProfile = null) {
32
112
  handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
33
113
  })
34
114
  return () => {
115
+ cleanupAllStagedUploads()
35
116
  try { if (typeof r === 'function') r() } catch {}
36
117
  }
37
118
  }
@@ -40,6 +121,53 @@ function normalizeMcpName(value) {
40
121
  return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
41
122
  }
42
123
 
124
+ const ICON_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox"
125
+
126
+ function etagMatches(ifNoneMatch, etag) {
127
+ if (!ifNoneMatch || !etag) return false
128
+ const raw = Array.isArray(ifNoneMatch) ? ifNoneMatch.join(',') : String(ifNoneMatch)
129
+ const trimmed = raw.trim()
130
+ if (!trimmed) return false
131
+ if (trimmed === '*') return true
132
+ const bare = (tag) => (tag.startsWith('W/') ? tag.slice(2) : tag)
133
+ const target = bare(etag.trim())
134
+ const tokens = trimmed.match(/(?:W\/)?"(?:\\.|[^"])*"|\*/g)
135
+ if (!tokens) return false
136
+ return tokens.some((token) => token === '*' || bare(token) === target)
137
+ }
138
+
139
+ function sendIconResponse(req, res, { buffer, contentType, etag, cacheControl }) {
140
+ const baseHeaders = {
141
+ 'Cache-Control': cacheControl,
142
+ ...(etag ? { 'ETag': etag } : {}),
143
+ 'X-Content-Type-Options': 'nosniff',
144
+ 'Content-Security-Policy': ICON_CSP,
145
+ }
146
+ if (etag && etagMatches(req.headers?.['if-none-match'], etag)) {
147
+ res.writeHead(304, baseHeaders)
148
+ return res.end()
149
+ }
150
+ res.writeHead(200, {
151
+ 'Content-Type': contentType || 'image/png',
152
+ ...baseHeaders,
153
+ })
154
+ return res.end(buffer)
155
+ }
156
+
157
+ /**
158
+ * Resolve one plugin's directory in O(1) without calling readMarketplace()
159
+ * across every sibling plugin and icon in the marketplace.
160
+ */
161
+ function resolvePluginIconDir(sourceId, name) {
162
+ const cleanName = name.toLowerCase()
163
+ const record = readState().plugins.find((p) => p.name.toLowerCase() === cleanName && p.sourceId === sourceId)
164
+ if (record) {
165
+ const inst = installedDir(record.name)
166
+ if (existsSync(inst)) return inst
167
+ }
168
+ return resolveMarketplacePluginDir(sourceId, name)
169
+ }
170
+
43
171
 
44
172
  async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
45
173
  const url = new URL(req.url, 'http://localhost')
@@ -52,14 +180,13 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
52
180
  const targetUrl = url.searchParams.get('u')
53
181
  if (!targetUrl) return sendJson(res, 400, { error: 'missing u parameter' })
54
182
  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",
183
+ const { buffer, contentType, etag, immutable } = await getOrFetchIcon(targetUrl)
184
+ return sendIconResponse(req, res, {
185
+ buffer,
186
+ contentType,
187
+ etag,
188
+ cacheControl: immutable ? 'public, max-age=31536000, immutable' : 'public, max-age=604800',
61
189
  })
62
- return res.end(buffer)
63
190
  } catch (err) {
64
191
  return sendJson(res, 502, { error: err.message })
65
192
  }
@@ -69,13 +196,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
69
196
  try {
70
197
  const sourceId = safeSegment(url.searchParams.get('sourceId'), 'source id')
71
198
  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)
199
+ const relPath = url.searchParams.get('path')
200
+ const dir = resolvePluginIconDir(sourceId, name)
75
201
  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)
202
+ const { buffer, contentType, etag, fileVersion } = await readLocalIconCached(dir, relPath, [sourceId, name, relPath])
203
+ const requestedVersion = url.searchParams.get('v')
204
+ const cacheControl = requestedVersion
205
+ ? (requestedVersion === fileVersion ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
206
+ : 'public, max-age=604800'
207
+ return sendIconResponse(req, res, { buffer, contentType, etag, cacheControl })
79
208
  } catch {
80
209
  return sendJson(res, 404, { error: 'Plugin icon not found' })
81
210
  }
@@ -86,6 +215,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
86
215
  return sendJson(res, 200, { groups: toolCallIconGroups() })
87
216
  }
88
217
 
218
+ if (method === 'GET' && path === '/at-plugins') {
219
+ return sendJson(res, 200, { plugins: listAtPlugins() })
220
+ }
221
+
89
222
  if (method === 'GET' && path === '/state') {
90
223
  const state = readState()
91
224
  const details = installedDetails()
@@ -151,9 +284,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
151
284
  if (path === '/skills/icon' && method === 'GET' && skills) {
152
285
  try {
153
286
  const item = skills.detail(url.searchParams.get('id'), false)
154
- const { buffer, contentType } = readLocalIcon(item.directory, item.iconPath)
155
- 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" })
156
- return res.end(buffer)
287
+ const { buffer, contentType, etag } = await readLocalIconCached(item.directory, item.iconPath, ['skill', item.id, item.iconPath])
288
+ return sendIconResponse(req, res, { buffer, contentType, etag, cacheControl: 'public, max-age=3600' })
157
289
  } catch { return sendJson(res, 404, { error: 'Icon not found' }) }
158
290
  }
159
291
 
@@ -161,12 +293,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
161
293
  if (method === 'GET' && path === '/market') {
162
294
  const rawSource = url.searchParams.get('sourceId') || url.searchParams.get('source') || 'anthropic'
163
295
  const sourceId = safeSegment(rawSource, 'source id')
164
- await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
165
- let rows = readMarketplace(sourceId)
166
- if (sourceId === 'local') {
167
- const names = new Set(rows.map(r => r.name))
168
- rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
169
- }
296
+ const rows = await withSourceLock(sourceId, async () => {
297
+ await ensureMarketCheckout(sourceId, sourceUrlOf(sourceId))
298
+ let plugins = readMarketplace(sourceId)
299
+ if (sourceId === 'local') {
300
+ const names = new Set(plugins.map(r => r.name))
301
+ plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
302
+ }
303
+ return plugins
304
+ })
170
305
  return sendJson(res, 200, { plugins: rows })
171
306
  }
172
307
 
@@ -174,16 +309,21 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
174
309
  requireSameOrigin(req)
175
310
  const body = await readJsonBody(req)
176
311
  const sourceId = safeSegment(body.sourceId || 'anthropic', 'source id')
177
- // Clone first if the source has never been fetched (fresh install), so a
178
- // first-launch refresh does not fail with "尚未克隆".
179
- await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
180
- await pullSource(sourceId)
181
- invalidateMarketplaceCache(sourceId)
182
- let plugins = readMarketplace(sourceId)
183
- if (sourceId === 'local') {
184
- const names = new Set(plugins.map(p => p.name))
185
- plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
186
- }
312
+ const plugins = await withSourceLock(sourceId, async () => {
313
+ // Clone first if the source has never been fetched (fresh install), so a
314
+ // first-launch refresh does not fail with "尚未克隆".
315
+ await ensureMarketCheckout(sourceId, sourceUrlOf(sourceId))
316
+ await pullSource(sourceId)
317
+ invalidateMarketplaceCache(sourceId)
318
+ invalidateLocalIconCache(sourceId)
319
+ invalidateAtPluginsCache()
320
+ let rows = readMarketplace(sourceId)
321
+ if (sourceId === 'local') {
322
+ const names = new Set(rows.map(r => r.name))
323
+ rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
324
+ }
325
+ return rows
326
+ })
187
327
  return sendJson(res, 200, { ok: true, plugins })
188
328
  }
189
329
 
@@ -200,17 +340,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
200
340
  const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
201
341
  if (!id) throw new Error('无法从该地址识别仓库')
202
342
 
203
- // Check duplicates BEFORE cloning
204
- const state = readState()
205
- const duplicate = findDuplicateSource(state, id, url)
206
- if (duplicate) {
207
- throw new Error(`该插件源已存在(${duplicate.name})`)
208
- }
209
-
210
- // Validate by cloning into the cache
211
- await ensureSourceCloned(id, url)
212
- const rows = readMarketplace(id)
213
- const count = Array.isArray(rows) ? rows.length : 0
343
+ const { pluginCount, marketName } = await withSourceLock(id, async () => {
344
+ // Check duplicates BEFORE cloning
345
+ const state = readState()
346
+ const duplicate = findDuplicateSource(state, id, url)
347
+ if (duplicate) {
348
+ throw new Error(`该插件源已存在(${duplicate.name})`)
349
+ }
350
+ // Validate by cloning into the cache
351
+ const checkout = await ensureMarketCheckout(id, url)
352
+ return { pluginCount: readMarketplace(id).length, marketName: readMarketplaceName(checkout) }
353
+ })
214
354
 
215
355
  const repoLabel = parsed ? `${parsed.owner}/${parsed.repo}` : (url.replace(/^https?:\/\//i, '').replace(/\.git$/i, ''))
216
356
 
@@ -219,25 +359,75 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
219
359
  sourceId: id,
220
360
  repoLabel,
221
361
  normalizedUrl: url,
222
- pluginCount: count,
223
- suggestedName: suggestSourceName(url),
362
+ pluginCount,
363
+ suggestedName: suggestSourceName(url, marketName),
224
364
  })
225
365
  }
226
366
 
227
367
  // ── local plugin inspection & import ──────────────────────────────────
228
368
  if (method === 'POST' && path === '/plugins/local/inspect') {
229
369
  requireSameOrigin(req)
230
- const body = await readJsonBody(req, 30_000_000)
231
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
232
- const result = await inspectLocalPlugin(target)
233
- return sendJson(res, 200, result)
370
+ disableUploadTimeouts(req, res)
371
+ const contentType = String(req.headers?.['content-type'] || '').toLowerCase()
372
+ let target = ''
373
+ let stagedUpload = null
374
+ if (contentType.includes('application/octet-stream')) {
375
+ const rawHeaderName = String(req.headers?.['x-upload-filename'] || '')
376
+ let filename = url.searchParams.get('filename') || ''
377
+ if (rawHeaderName) {
378
+ try { filename = decodeURIComponent(rawHeaderName) } catch { filename = rawHeaderName }
379
+ }
380
+ stagedUpload = await saveUploadedStream(req, filename, MAX_UPLOAD_BYTES)
381
+ target = stagedUpload.file
382
+ } else {
383
+ const body = await readJsonBody(req, 30_000_000)
384
+ if (body.data) {
385
+ const file = await saveUploadedZip(body.data, body.filename)
386
+ stagedUpload = { file, uploadDir: dirname(file) }
387
+ target = file
388
+ } else {
389
+ target = body.path
390
+ }
391
+ }
392
+ let result
393
+ try {
394
+ result = await inspectLocalPlugin(target)
395
+ } catch (err) {
396
+ if (stagedUpload) safeRmDir(stagedUpload.uploadDir)
397
+ throw err
398
+ }
399
+ // The extraction is only for this preview: clean up the temp extract dir,
400
+ // while staging valid streamed uploads behind an opaque token so confirm does not re-upload.
401
+ if (result.tempExtractDir) safeRmDir(result.tempExtractDir)
402
+ if (!result.ok && stagedUpload) {
403
+ safeRmDir(stagedUpload.uploadDir)
404
+ }
405
+ const uploadId = (result.ok && stagedUpload) ? registerStagedUpload(stagedUpload.file, stagedUpload.uploadDir) : undefined
406
+ const { tempExtractDir, effectiveDir, entries, ...preview } = result
407
+ return sendJson(res, 200, uploadId ? { ...preview, uploadId } : preview)
408
+ }
409
+
410
+ if (method === 'POST' && path === '/plugins/local/upload-cancel') {
411
+ requireSameOrigin(req)
412
+ const body = await readJsonBody(req)
413
+ discardStagedUpload(body?.uploadId)
414
+ return sendJson(res, 200, { ok: true })
234
415
  }
235
416
 
236
417
  if (method === 'POST' && path === '/plugins/local/import') {
237
418
  requireSameOrigin(req)
419
+ disableUploadTimeouts(req, res)
238
420
  const body = await readJsonBody(req, 30_000_000)
239
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
240
- const result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
421
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
422
+ let result
423
+ try {
424
+ result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
425
+ } finally {
426
+ if (tempUploadDir) safeRmDir(tempUploadDir)
427
+ }
428
+ if (stagedId) discardStagedUpload(stagedId)
429
+ invalidateLocalIconCache('local')
430
+ invalidateAtPluginsCache()
241
431
  return sendJson(res, 200, result)
242
432
  }
243
433
 
@@ -245,9 +435,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
245
435
  // junction into $DSH_HOME/skills, then a hot refresh of the Skills tab.
246
436
  if (method === 'POST' && path === '/skills/import') {
247
437
  requireSameOrigin(req)
438
+ disableUploadTimeouts(req, res)
248
439
  const body = await readJsonBody(req, 30_000_000)
249
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
250
- const result = await importLocalSkills(target, { overwrite: body.overwrite === true })
440
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
441
+ let result
442
+ try {
443
+ result = await importLocalSkills(target, {
444
+ overwrite: body.overwrite === true,
445
+ overwriteNames: Array.isArray(body.overwriteNames) ? body.overwriteNames.map(String) : null,
446
+ })
447
+ } finally {
448
+ if (tempUploadDir) safeRmDir(tempUploadDir)
449
+ }
450
+ if (stagedId) discardStagedUpload(stagedId)
251
451
  skills?.refresh()
252
452
  return sendJson(res, 200, result)
253
453
  }
@@ -255,9 +455,20 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
255
455
  // An uploaded marketplace becomes its own plugin source tab.
256
456
  if (method === 'POST' && path === '/marketplaces/import') {
257
457
  requireSameOrigin(req)
458
+ disableUploadTimeouts(req, res)
258
459
  const body = await readJsonBody(req, 30_000_000)
259
- const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
260
- const result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true })
460
+ const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
461
+ let result
462
+ try {
463
+ result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true, target: body.target })
464
+ } finally {
465
+ if (tempUploadDir) safeRmDir(tempUploadDir)
466
+ }
467
+ if (stagedId) discardStagedUpload(stagedId)
468
+ if (result?.sourceId) {
469
+ invalidateLocalIconCache(result.sourceId)
470
+ }
471
+ invalidateAtPluginsCache()
261
472
  return sendJson(res, 200, result)
262
473
  }
263
474
 
@@ -275,28 +486,29 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
275
486
  const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
276
487
  if (!id) throw new Error('无法从该地址识别仓库')
277
488
 
278
- const state = readState()
279
- const duplicate = findDuplicateSource(state, id, url)
280
- if (duplicate) {
281
- throw new Error(`该插件源已存在(${duplicate.name})`)
489
+ const validateUnique = (state) => {
490
+ const duplicate = findDuplicateSource(state, id, url)
491
+ if (duplicate) {
492
+ throw new Error(`该插件源已存在(${duplicate.name})`)
493
+ }
494
+ if (state.sources.some((s) => s.name.trim().toLowerCase() === name.toLowerCase())) {
495
+ throw new Error(`已存在同名的插件源「${name}」,请换一个名称`)
496
+ }
282
497
  }
283
498
 
284
- // Check name duplication (e.g. user naming two sources with the same label)
285
- if (state.sources.some((s) => s.name.trim().toLowerCase() === name.toLowerCase())) {
286
- throw new Error(`已存在同名的插件源「${name}」,请换一个名称`)
287
- }
288
-
289
- await ensureSourceCloned(id, url)
290
- const rows = readMarketplace(id)
291
- const count = Array.isArray(rows) ? rows.length : 0
499
+ return sendJson(res, 200, await withSourceLock(id, async () => {
500
+ validateUnique(readState())
501
+ await ensureMarketCheckout(id, url)
502
+ const plugins = readMarketplace(id)
292
503
 
293
- state.sources.push({ id, name, url, addedAt: Date.now() })
294
- writeState(state)
295
- return sendJson(res, 200, {
296
- ok: true,
297
- source: state.sources[state.sources.length - 1],
298
- pluginCount: count,
299
- })
504
+ // Re-read state after awaiting clone so concurrent mutations (e.g. plugin toggles) are preserved.
505
+ const latestState = readState()
506
+ validateUnique(latestState)
507
+ const source = { id, name, url, addedAt: Date.now() }
508
+ latestState.sources.push(source)
509
+ writeState(latestState)
510
+ return { ok: true, source, plugins, pluginCount: plugins.length }
511
+ }))
300
512
  }
301
513
 
302
514
  if (method === 'POST' && path === '/sources/reorder') {
@@ -330,18 +542,27 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
330
542
  if (method === 'DELETE' && path.startsWith('/sources/')) {
331
543
  requireSameOrigin(req)
332
544
  const sourceId = safeSegment(path.slice('/sources/'.length), 'source id')
333
- const state = readState()
334
- const source = state.sources.find((s) => s.id === sourceId)
335
- if (!source) throw new Error('插件源不存在')
336
- if (source.builtin) throw new Error('内置源不可删除')
337
- const used = state.plugins.some((p) => p.sourceId === sourceId)
338
- if (used) throw new Error('该源下仍有已安装插件,请先卸载')
339
- // The remote checkout pool is shared by marketplaces. Only remove this
340
- // source's own clone or uploaded marketplace copy.
341
- if (sourceId !== 'remote') removeManagedDir(sourceCacheDir(sourceId))
342
- state.sources = state.sources.filter((s) => s.id !== sourceId)
343
- writeState(state)
344
- invalidateMarketplaceCache(sourceId)
545
+ await withSourceLock(sourceId, async () => {
546
+ const state = readState()
547
+ const source = state.sources.find((s) => s.id === sourceId)
548
+ if (!source) throw new Error('插件源不存在')
549
+ if (source.builtin) throw new Error('内置源不可删除')
550
+ const used = state.plugins.some((p) => p.sourceId === sourceId)
551
+ if (used) throw new Error('该源下仍有已安装插件,请先卸载')
552
+ // The remote checkout pool is shared by marketplaces. Only remove this
553
+ // source's own clone or uploaded marketplace copy.
554
+ if (sourceId === 'local') cleanupAllStagedUploads()
555
+ if (sourceId !== 'remote') {
556
+ await removeManagedDirAsync(sourceCacheDir(sourceId), { deferCleanup: /^https?:\/\//i.test(source.url) })
557
+ }
558
+ const latestState = readState()
559
+ latestState.sources = latestState.sources.filter((s) => s.id !== sourceId)
560
+ if (Array.isArray(latestState.tabOrder)) latestState.tabOrder = latestState.tabOrder.filter((id) => id !== sourceId)
561
+ writeState(latestState)
562
+ invalidateMarketplaceCache(sourceId)
563
+ invalidateLocalIconCache(sourceId)
564
+ invalidateAtPluginsCache()
565
+ })
345
566
  return sendJson(res, 200, { ok: true })
346
567
  }
347
568
 
@@ -365,24 +586,27 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
365
586
  for (const item of block.insert) {
366
587
  if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
367
588
  const cfg = item.config || {}
368
- if (pluginTools?.[`user-mcp::${cfg.serverName}`]?.pluginOAuthOwned && remoteConfigFromEntry(cfg)) continue
589
+ const ownership = pluginTools?.[`user-mcp::${cfg.serverName}`]
590
+ if (ownership?.pluginConnectorOwned || (ownership?.pluginOAuthOwned && remoteConfigFromEntry(cfg))) continue
369
591
  if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
370
592
  state.userMcps.push(userMcpConfig(cfg.serverName, {
371
593
  transport: cfg.transport, url: cfg.url, command: cfg.command,
372
- args: Array.isArray(cfg.args) ? cfg.args : [], env: cfg.env || {},
373
- headers: cfg.headers || {}, oauth: cfg.oauth || 'none',
594
+ args: Array.isArray(cfg.args) ? cfg.args : [], cwd: cfg.cwd,
595
+ env: cfg.env || {}, headers: cfg.headers || {}, oauth: cfg.oauth || 'none',
374
596
  }))
375
597
  changed = true
376
598
  }
377
599
  }
378
600
  }
379
601
  if (changed) writeState(state)
602
+ const toolsState = readMcpToolsState()
380
603
  const mcps = state.userMcps
381
604
  .filter((x) => x && x.name)
382
605
  .map((x) => {
383
606
  const entry = getConnectorEntry('user-mcp', x.name)
384
- const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
607
+ const remote = remoteConfigFromEntry(entry?.config) || toolsState[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
385
608
  const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
609
+ const oauthAuthenticated = isOAuthConnectorAuthenticated('user-mcp', x.name, remote, toolsState)
386
610
  // The live registration says what is *running*; the saved definition
387
611
  // says what the editor should show. The client id comes from the
388
612
  // credential record, since the definition never stores the secret.
@@ -397,7 +621,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
397
621
  // opinion, so a cleared field stays cleared.
398
622
  oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
399
623
  oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
400
- } : {}),
624
+ } : entry?.config?.headers ? { headers: entry.config.headers } : {}),
625
+ oauthAuthenticated,
401
626
  enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
402
627
  }
403
628
  })
@@ -414,7 +639,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
414
639
  if (method === 'POST' && path === '/mcps/verify') {
415
640
  requireSameOrigin(req)
416
641
  const body = await readJsonBody(req)
417
- const name = String(body.name || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
642
+ const name = normalizeMcpName(body.name)
418
643
  const result = await verifyConnectorAuth('user-mcp', name, body)
419
644
  return sendJson(res, 200, result)
420
645
  }
@@ -423,12 +648,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
423
648
  requireSameOrigin(req)
424
649
  const body = await readJsonBody(req)
425
650
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
426
- const result = saveConnectorAuth('user-mcp', name, body)
651
+ const probe = await probeConnectorAuth('user-mcp', name, body)
652
+ if (!probe.ok) return sendJson(res, 200, { ok: false, error: probe.error })
653
+ const result = saveConnectorAuth('user-mcp', name, body, { probe })
427
654
  if (result && result.ok) {
428
655
  const state = readState()
429
656
  if (!Array.isArray(state.userMcps)) state.userMcps = []
430
657
  state.userMcps = state.userMcps.filter((x) => x && x.name !== name)
431
- state.userMcps.push(userMcpConfig(name, body))
658
+ state.userMcps.push(userMcpConfig(name, { ...body, ...probe.definition }))
432
659
  writeState(state)
433
660
  }
434
661
  // A rejected create registered nothing, so there is nothing to apply.
@@ -445,32 +672,47 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
445
672
  ? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
446
673
  : null
447
674
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
448
- const state = readState()
675
+ let state = readState()
449
676
  if (!Array.isArray(state.userMcps)) state.userMcps = []
450
- const idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
677
+ let idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
451
678
  if (idx < 0) throw new Error(`MCP 不存在:${previousName || name}`)
679
+ const oldName = previousName || name
680
+ if (oldName !== name && state.userMcps.some(item => item?.name === name)) {
681
+ throw new Error(`已存在同名 MCP:${name}`)
682
+ }
683
+ const saved = state.userMcps[idx]
684
+ const wasEnabled = !!getConnectorEntry('user-mcp', oldName)
685
+ const enable = wasEnabled || body.enable === true
686
+ const cfg = { ...userMcpConfig(name, body, saved), oauthClientSecret: body.oauthClientSecret }
687
+ let probe
688
+ if (enable) {
689
+ probe = await probeUserMcpUpdate(oldName, name, cfg)
690
+ if (!probe.ok) return sendJson(res, 200, { ok: false, error: probe.error })
691
+ state = readState()
692
+ idx = state.userMcps?.findIndex(x => x?.name === oldName) ?? -1
693
+ if (idx < 0 || JSON.stringify(state.userMcps[idx]) !== JSON.stringify(saved)
694
+ || !!getConnectorEntry('user-mcp', oldName) !== wasEnabled) {
695
+ return sendJson(res, 200, { ok: false, error: 'MCP 配置或开关已变更,请刷新后重试' })
696
+ }
697
+ Object.assign(cfg, probe.definition)
698
+ }
452
699
  if (previousName && previousName !== name) {
453
- // Capture enablement before the rename: a disabled server registers
454
- // nothing, so asking HMR to start its id would target an entry that
455
- // does not exist.
456
- const renamingEnabled = !!getConnectorEntry('user-mcp', previousName)
457
- const renamed = renameUserMcp(previousName, name, body)
700
+ const renamed = renameUserMcp(previousName, name, cfg, { enable, probe })
458
701
  // A rename that failed registered nothing, so there is nothing to apply.
459
702
  if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
460
703
  return sendJson(res, 200, scheduledResult(
461
- renamed, applyProfile, renamingEnabled ? [getConnectorId('user-mcp', name)] : []))
704
+ renamed, applyProfile, enable ? [getConnectorId('user-mcp', name)] : []))
462
705
  }
463
- const wasEnabled = !!getConnectorEntry('user-mcp', name)
464
706
  let result = { ok: true }
465
- if (wasEnabled) {
466
- result = saveConnectorAuth('user-mcp', name, body)
707
+ if (enable) {
708
+ result = saveConnectorAuth('user-mcp', name, cfg, { probe })
467
709
  if (!result || !result.ok) return sendJson(res, 200, result)
468
710
  }
469
711
  // Pass the stored record so an edit keeps the URL history a later delete
470
712
  // needs to find every credential this server ever issued.
471
- state.userMcps[idx] = userMcpConfig(name, body, state.userMcps[idx])
713
+ state.userMcps[idx] = userMcpConfig(name, cfg, state.userMcps[idx])
472
714
  writeState(state)
473
- return sendJson(res, 200, scheduledResult(result, applyProfile, wasEnabled ? [getConnectorId('user-mcp', name)] : []))
715
+ return sendJson(res, 200, enable ? scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]) : result)
474
716
  }
475
717
 
476
718
  // One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
@@ -498,11 +740,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
498
740
  const cfg = (state.userMcps || []).find((x) => x && x.name === name)
499
741
  if (!cfg) throw new Error(`MCP 不存在:${name}`)
500
742
  if (body.enabled !== false) {
501
- const result = saveConnectorAuth('user-mcp', name, cfg)
743
+ const result = await enableConnector('user-mcp', name, cfg, {
744
+ canEnable: () => readState().userMcps?.some(item => item?.name === name && JSON.stringify(item) === JSON.stringify(cfg)),
745
+ })
502
746
  // A rejected enable registered nothing: do not schedule a reconcile.
503
747
  if (!result || !result.ok) return sendJson(res, 200, result)
504
748
  return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
505
749
  }
750
+ const liveHeaders = getConnectorEntry('user-mcp', name)?.config?.headers
751
+ if (liveHeaders) writeState({ ...state, userMcps: state.userMcps.map(item => item === cfg ? { ...cfg, headers: liveHeaders } : item) })
506
752
  unregisterConnector('user-mcp', name)
507
753
  return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
508
754
  }
@@ -562,10 +808,16 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
562
808
  const pluginName = safeSegment(parts[0], 'plugin name')
563
809
  const connectorName = safeSegment(parts[2], 'connector name')
564
810
  const body = await readJsonBody(req)
565
- const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
566
- // A rejected toggle registered nothing: do not schedule a reconcile.
567
- if (!result || !result.ok) return sendJson(res, 200, result)
568
- return sendJson(res, 200, scheduledResult(result, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
811
+ cancelActivePluginProbes(pluginName, connectorName)
812
+ const outcome = await withPluginLock(pluginName, async () => {
813
+ const pluginRec = readState().plugins.find(plugin => plugin.name === pluginName)
814
+ if (!pluginRec) return { ok: false, error: '插件未安装或已卸载' }
815
+ const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
816
+ if (!canEnable() && body.enabled !== false) return { ok: false, error: '请先启用所属插件' }
817
+ const result = await toggleConnector(pluginName, connectorName, body.enabled !== false, { canEnable })
818
+ return withPluginDetail(result, pluginName)
819
+ })
820
+ return sendJson(res, 200, scheduledIfOk(outcome, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
569
821
  }
570
822
 
571
823
  if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
@@ -587,11 +839,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
587
839
  const pluginName = safeSegment(parts[0], 'plugin name')
588
840
  const connectorName = safeSegment(parts[2], 'connector name')
589
841
  const body = await readJsonBody(req)
590
- if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
591
- return sendJson(res, 404, { ok: false, error: '插件未安装或已卸载' })
592
- }
593
- const result = saveConnectorAuth(pluginName, connectorName, body, { pluginOwned: true })
594
- return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
842
+ cancelActivePluginProbes(pluginName, connectorName)
843
+ const outcome = await withPluginLock(pluginName, async () => {
844
+ if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
845
+ return { status: 404, body: { ok: false, error: '插件未安装或已卸载' } }
846
+ }
847
+ const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
848
+ if (!canEnable()) return { status: 200, body: { ok: false, error: '请先启用所属插件' } }
849
+ const result = await enableConnector(pluginName, connectorName, body, { pluginOwned: true, canEnable, reuseStdioCache: false })
850
+ return { status: 200, body: scheduledIfOk(withPluginDetail(result, pluginName), applyProfile, [getConnectorId(pluginName, connectorName)]) }
851
+ })
852
+ return sendJson(res, outcome.status, outcome.body)
595
853
  }
596
854
 
597
855
  // ── plugin detail ────────────────────────────────────────────────────
@@ -610,6 +868,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
610
868
  if (!detail && row?.source && typeof row.source === 'object') {
611
869
  await materializePlugin(sourceId, pluginName, row.source)
612
870
  invalidateMarketplaceCache(sourceId)
871
+ invalidateLocalIconCache(sourceId)
872
+ invalidateAtPluginsCache()
613
873
  row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
614
874
  detail = pluginDetail(sourceId, pluginName, row.source, row)
615
875
  }
@@ -667,14 +927,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
667
927
  pluginName,
668
928
  })
669
929
  invalidateMarketplaceCache(sourceId)
670
- return sendJson(res, 200, scheduledResult(result, applyProfile))
930
+ invalidateLocalIconCache(sourceId)
931
+ invalidateAtPluginsCache()
932
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
671
933
  }
672
934
 
673
935
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
674
936
  requireSameOrigin(req)
675
937
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
676
938
  const body = await readJsonBody(req)
677
- return sendJson(res, 200, scheduledResult(await togglePlugin(pluginName, body.enabled === true), applyProfile))
939
+ const result = await togglePlugin(pluginName, body.enabled === true, { onConnectorReady: (id) => applyProfile?.([id]) })
940
+ const payload = scheduledIfOk(withPluginDetail(result, pluginName), applyProfile)
941
+ invalidateAtPluginsCache()
942
+ return sendJson(res, 200, payload)
678
943
  }
679
944
 
680
945
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
@@ -682,7 +947,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
682
947
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
683
948
  const result = await updatePlugin(pluginName)
684
949
  invalidateMarketplaceCache()
685
- return sendJson(res, 200, scheduledResult(result, applyProfile))
950
+ invalidateLocalIconCache()
951
+ invalidateAtPluginsCache()
952
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
686
953
  }
687
954
 
688
955
  if (method === 'POST' && path === '/restart') {
@@ -725,12 +992,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
725
992
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
726
993
  const result = await uninstallPlugin(pluginName)
727
994
  invalidateMarketplaceCache()
728
- return sendJson(res, 200, scheduledResult(result, applyProfile))
995
+ invalidateLocalIconCache()
996
+ invalidateAtPluginsCache()
997
+ return sendJson(res, 200, scheduledIfOk(result, applyProfile))
729
998
  }
730
999
 
731
1000
  return sendJson(res, 404, { error: 'not found' })
732
1001
  } catch (error) {
733
1002
  const status = (error && typeof error === 'object' && error.status) ? error.status : 500
1003
+ if (status === 413 && res) {
1004
+ try { res.setHeader?.('Connection', 'close') } catch {}
1005
+ }
734
1006
  sendJson(res, status, { error: error instanceof Error ? error.message : String(error) })
735
1007
  }
736
1008
  }
@@ -743,6 +1015,16 @@ function requireSameOrigin(req) {
743
1015
  }
744
1016
  }
745
1017
 
1018
+ function ensureMarketCheckout(sourceId, url) {
1019
+ return ensureSourceCloned(sourceId, url, {
1020
+ onCloned() {
1021
+ invalidateMarketplaceCache(sourceId)
1022
+ invalidateLocalIconCache(sourceId)
1023
+ invalidateAtPluginsCache()
1024
+ },
1025
+ })
1026
+ }
1027
+
746
1028
  function sourceUrlOf(sourceId) {
747
1029
  const state = readState()
748
1030
  const source = state.sources.find((s) => s.id === sourceId)