universal-plugin-hub 1.1.0 → 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/README.md +1 -1
- package/client/client.js +2891 -909
- package/package.json +1 -1
- package/src/icons.js +219 -36
- package/src/index.js +26 -2
- package/src/install.js +3088 -2649
- package/src/local.js +439 -71
- package/src/market.js +48 -17
- package/src/oauth-bridge.js +1 -1
- package/src/oauth.js +2 -1
- package/src/parser.js +1246 -459
- package/src/routes.js +369 -119
- package/src/skill-uploads.js +116 -12
- package/src/skills.js +8 -1
- package/src/store.js +171 -31
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 {
|
|
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,
|
|
14
|
-
import { getOrFetchIcon,
|
|
14
|
+
import { readMarketplace, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
|
|
15
|
+
import { getOrFetchIcon, readLocalIconCached, invalidateLocalIconCache } from './icons.js'
|
|
15
16
|
import {
|
|
16
17
|
installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered, toolCallIconGroups,
|
|
17
|
-
toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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,13 +191,15 @@ 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
|
|
73
|
-
const
|
|
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 } =
|
|
77
|
-
|
|
78
|
-
|
|
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
|
}
|
|
@@ -151,9 +275,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
151
275
|
if (path === '/skills/icon' && method === 'GET' && skills) {
|
|
152
276
|
try {
|
|
153
277
|
const item = skills.detail(url.searchParams.get('id'), false)
|
|
154
|
-
const { buffer, contentType } =
|
|
155
|
-
|
|
156
|
-
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' })
|
|
157
280
|
} catch { return sendJson(res, 404, { error: 'Icon not found' }) }
|
|
158
281
|
}
|
|
159
282
|
|
|
@@ -174,16 +297,20 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
174
297
|
requireSameOrigin(req)
|
|
175
298
|
const body = await readJsonBody(req)
|
|
176
299
|
const sourceId = safeSegment(body.sourceId || 'anthropic', 'source id')
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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
|
+
})
|
|
187
314
|
return sendJson(res, 200, { ok: true, plugins })
|
|
188
315
|
}
|
|
189
316
|
|
|
@@ -200,17 +327,18 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
200
327
|
const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
|
|
201
328
|
if (!id) throw new Error('无法从该地址识别仓库')
|
|
202
329
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
+
})
|
|
214
342
|
|
|
215
343
|
const repoLabel = parsed ? `${parsed.owner}/${parsed.repo}` : (url.replace(/^https?:\/\//i, '').replace(/\.git$/i, ''))
|
|
216
344
|
|
|
@@ -227,17 +355,66 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
227
355
|
// ── local plugin inspection & import ──────────────────────────────────
|
|
228
356
|
if (method === 'POST' && path === '/plugins/local/inspect') {
|
|
229
357
|
requireSameOrigin(req)
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
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 })
|
|
234
403
|
}
|
|
235
404
|
|
|
236
405
|
if (method === 'POST' && path === '/plugins/local/import') {
|
|
237
406
|
requireSameOrigin(req)
|
|
407
|
+
disableUploadTimeouts(req, res)
|
|
238
408
|
const body = await readJsonBody(req, 30_000_000)
|
|
239
|
-
const target
|
|
240
|
-
|
|
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')
|
|
241
418
|
return sendJson(res, 200, result)
|
|
242
419
|
}
|
|
243
420
|
|
|
@@ -245,9 +422,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
245
422
|
// junction into $DSH_HOME/skills, then a hot refresh of the Skills tab.
|
|
246
423
|
if (method === 'POST' && path === '/skills/import') {
|
|
247
424
|
requireSameOrigin(req)
|
|
425
|
+
disableUploadTimeouts(req, res)
|
|
248
426
|
const body = await readJsonBody(req, 30_000_000)
|
|
249
|
-
const target
|
|
250
|
-
|
|
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)
|
|
251
438
|
skills?.refresh()
|
|
252
439
|
return sendJson(res, 200, result)
|
|
253
440
|
}
|
|
@@ -255,9 +442,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
255
442
|
// An uploaded marketplace becomes its own plugin source tab.
|
|
256
443
|
if (method === 'POST' && path === '/marketplaces/import') {
|
|
257
444
|
requireSameOrigin(req)
|
|
445
|
+
disableUploadTimeouts(req, res)
|
|
258
446
|
const body = await readJsonBody(req, 30_000_000)
|
|
259
|
-
const target
|
|
260
|
-
|
|
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
|
+
}
|
|
261
458
|
return sendJson(res, 200, result)
|
|
262
459
|
}
|
|
263
460
|
|
|
@@ -275,28 +472,30 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
275
472
|
const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
|
|
276
473
|
if (!id) throw new Error('无法从该地址识别仓库')
|
|
277
474
|
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
+
}
|
|
282
483
|
}
|
|
283
484
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
await ensureSourceCloned(id, url)
|
|
290
|
-
const rows = readMarketplace(id)
|
|
291
|
-
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
|
|
292
490
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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
|
+
}))
|
|
300
499
|
}
|
|
301
500
|
|
|
302
501
|
if (method === 'POST' && path === '/sources/reorder') {
|
|
@@ -330,18 +529,24 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
330
529
|
if (method === 'DELETE' && path.startsWith('/sources/')) {
|
|
331
530
|
requireSameOrigin(req)
|
|
332
531
|
const sourceId = safeSegment(path.slice('/sources/'.length), 'source id')
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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
|
+
})
|
|
345
550
|
return sendJson(res, 200, { ok: true })
|
|
346
551
|
}
|
|
347
552
|
|
|
@@ -365,24 +570,27 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
365
570
|
for (const item of block.insert) {
|
|
366
571
|
if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
|
|
367
572
|
const cfg = item.config || {}
|
|
368
|
-
|
|
573
|
+
const ownership = pluginTools?.[`user-mcp::${cfg.serverName}`]
|
|
574
|
+
if (ownership?.pluginConnectorOwned || (ownership?.pluginOAuthOwned && remoteConfigFromEntry(cfg))) continue
|
|
369
575
|
if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
|
|
370
576
|
state.userMcps.push(userMcpConfig(cfg.serverName, {
|
|
371
577
|
transport: cfg.transport, url: cfg.url, command: cfg.command,
|
|
372
|
-
args: Array.isArray(cfg.args) ? cfg.args : [],
|
|
373
|
-
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',
|
|
374
580
|
}))
|
|
375
581
|
changed = true
|
|
376
582
|
}
|
|
377
583
|
}
|
|
378
584
|
}
|
|
379
585
|
if (changed) writeState(state)
|
|
586
|
+
const toolsState = readMcpToolsState()
|
|
380
587
|
const mcps = state.userMcps
|
|
381
588
|
.filter((x) => x && x.name)
|
|
382
589
|
.map((x) => {
|
|
383
590
|
const entry = getConnectorEntry('user-mcp', x.name)
|
|
384
|
-
const remote = remoteConfigFromEntry(entry?.config) ||
|
|
591
|
+
const remote = remoteConfigFromEntry(entry?.config) || toolsState[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
|
|
385
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)
|
|
386
594
|
// The live registration says what is *running*; the saved definition
|
|
387
595
|
// says what the editor should show. The client id comes from the
|
|
388
596
|
// credential record, since the definition never stores the secret.
|
|
@@ -397,7 +605,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
397
605
|
// opinion, so a cleared field stays cleared.
|
|
398
606
|
oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
|
|
399
607
|
oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
|
|
400
|
-
} : {}),
|
|
608
|
+
} : entry?.config?.headers ? { headers: entry.config.headers } : {}),
|
|
609
|
+
oauthAuthenticated,
|
|
401
610
|
enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
|
|
402
611
|
}
|
|
403
612
|
})
|
|
@@ -414,7 +623,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
414
623
|
if (method === 'POST' && path === '/mcps/verify') {
|
|
415
624
|
requireSameOrigin(req)
|
|
416
625
|
const body = await readJsonBody(req)
|
|
417
|
-
const name =
|
|
626
|
+
const name = normalizeMcpName(body.name)
|
|
418
627
|
const result = await verifyConnectorAuth('user-mcp', name, body)
|
|
419
628
|
return sendJson(res, 200, result)
|
|
420
629
|
}
|
|
@@ -423,12 +632,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
423
632
|
requireSameOrigin(req)
|
|
424
633
|
const body = await readJsonBody(req)
|
|
425
634
|
const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
|
|
426
|
-
const
|
|
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 })
|
|
427
638
|
if (result && result.ok) {
|
|
428
639
|
const state = readState()
|
|
429
640
|
if (!Array.isArray(state.userMcps)) state.userMcps = []
|
|
430
641
|
state.userMcps = state.userMcps.filter((x) => x && x.name !== name)
|
|
431
|
-
state.userMcps.push(userMcpConfig(name, body))
|
|
642
|
+
state.userMcps.push(userMcpConfig(name, { ...body, ...probe.definition }))
|
|
432
643
|
writeState(state)
|
|
433
644
|
}
|
|
434
645
|
// A rejected create registered nothing, so there is nothing to apply.
|
|
@@ -445,32 +656,47 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
445
656
|
? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
|
|
446
657
|
: null
|
|
447
658
|
const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
|
|
448
|
-
|
|
659
|
+
let state = readState()
|
|
449
660
|
if (!Array.isArray(state.userMcps)) state.userMcps = []
|
|
450
|
-
|
|
661
|
+
let idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
|
|
451
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
|
+
}
|
|
452
683
|
if (previousName && previousName !== name) {
|
|
453
|
-
|
|
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)
|
|
684
|
+
const renamed = renameUserMcp(previousName, name, cfg, { enable, probe })
|
|
458
685
|
// A rename that failed registered nothing, so there is nothing to apply.
|
|
459
686
|
if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
|
|
460
687
|
return sendJson(res, 200, scheduledResult(
|
|
461
|
-
renamed, applyProfile,
|
|
688
|
+
renamed, applyProfile, enable ? [getConnectorId('user-mcp', name)] : []))
|
|
462
689
|
}
|
|
463
|
-
const wasEnabled = !!getConnectorEntry('user-mcp', name)
|
|
464
690
|
let result = { ok: true }
|
|
465
|
-
if (
|
|
466
|
-
result = saveConnectorAuth('user-mcp', name,
|
|
691
|
+
if (enable) {
|
|
692
|
+
result = saveConnectorAuth('user-mcp', name, cfg, { probe })
|
|
467
693
|
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
468
694
|
}
|
|
469
695
|
// Pass the stored record so an edit keeps the URL history a later delete
|
|
470
696
|
// needs to find every credential this server ever issued.
|
|
471
|
-
state.userMcps[idx] = userMcpConfig(name,
|
|
697
|
+
state.userMcps[idx] = userMcpConfig(name, cfg, state.userMcps[idx])
|
|
472
698
|
writeState(state)
|
|
473
|
-
return sendJson(res, 200, scheduledResult(result, applyProfile,
|
|
699
|
+
return sendJson(res, 200, enable ? scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]) : result)
|
|
474
700
|
}
|
|
475
701
|
|
|
476
702
|
// One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
|
|
@@ -498,11 +724,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
498
724
|
const cfg = (state.userMcps || []).find((x) => x && x.name === name)
|
|
499
725
|
if (!cfg) throw new Error(`MCP 不存在:${name}`)
|
|
500
726
|
if (body.enabled !== false) {
|
|
501
|
-
const result =
|
|
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
|
+
})
|
|
502
730
|
// A rejected enable registered nothing: do not schedule a reconcile.
|
|
503
731
|
if (!result || !result.ok) return sendJson(res, 200, result)
|
|
504
732
|
return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
|
|
505
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) })
|
|
506
736
|
unregisterConnector('user-mcp', name)
|
|
507
737
|
return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
|
|
508
738
|
}
|
|
@@ -562,10 +792,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
562
792
|
const pluginName = safeSegment(parts[0], 'plugin name')
|
|
563
793
|
const connectorName = safeSegment(parts[2], 'connector name')
|
|
564
794
|
const body = await readJsonBody(req)
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
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)] : []))
|
|
569
806
|
}
|
|
570
807
|
|
|
571
808
|
if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
|
|
@@ -587,11 +824,17 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
587
824
|
const pluginName = safeSegment(parts[0], 'plugin name')
|
|
588
825
|
const connectorName = safeSegment(parts[2], 'connector name')
|
|
589
826
|
const body = await readJsonBody(req)
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
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)
|
|
595
838
|
}
|
|
596
839
|
|
|
597
840
|
// ── plugin detail ────────────────────────────────────────────────────
|
|
@@ -610,6 +853,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
610
853
|
if (!detail && row?.source && typeof row.source === 'object') {
|
|
611
854
|
await materializePlugin(sourceId, pluginName, row.source)
|
|
612
855
|
invalidateMarketplaceCache(sourceId)
|
|
856
|
+
invalidateLocalIconCache(sourceId)
|
|
613
857
|
row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
|
|
614
858
|
detail = pluginDetail(sourceId, pluginName, row.source, row)
|
|
615
859
|
}
|
|
@@ -667,14 +911,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
667
911
|
pluginName,
|
|
668
912
|
})
|
|
669
913
|
invalidateMarketplaceCache(sourceId)
|
|
670
|
-
|
|
914
|
+
invalidateLocalIconCache(sourceId)
|
|
915
|
+
return sendJson(res, 200, scheduledIfOk(result, applyProfile))
|
|
671
916
|
}
|
|
672
917
|
|
|
673
918
|
if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
|
|
674
919
|
requireSameOrigin(req)
|
|
675
920
|
const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
|
|
676
921
|
const body = await readJsonBody(req)
|
|
677
|
-
return sendJson(res, 200,
|
|
922
|
+
return sendJson(res, 200, scheduledIfOk(await togglePlugin(pluginName, body.enabled === true), applyProfile))
|
|
678
923
|
}
|
|
679
924
|
|
|
680
925
|
if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
|
|
@@ -682,7 +927,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
682
927
|
const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
|
|
683
928
|
const result = await updatePlugin(pluginName)
|
|
684
929
|
invalidateMarketplaceCache()
|
|
685
|
-
|
|
930
|
+
invalidateLocalIconCache()
|
|
931
|
+
return sendJson(res, 200, scheduledIfOk(result, applyProfile))
|
|
686
932
|
}
|
|
687
933
|
|
|
688
934
|
if (method === 'POST' && path === '/restart') {
|
|
@@ -725,12 +971,16 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
|
|
|
725
971
|
const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
|
|
726
972
|
const result = await uninstallPlugin(pluginName)
|
|
727
973
|
invalidateMarketplaceCache()
|
|
728
|
-
|
|
974
|
+
invalidateLocalIconCache()
|
|
975
|
+
return sendJson(res, 200, scheduledIfOk(result, applyProfile))
|
|
729
976
|
}
|
|
730
977
|
|
|
731
978
|
return sendJson(res, 404, { error: 'not found' })
|
|
732
979
|
} catch (error) {
|
|
733
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
|
+
}
|
|
734
984
|
sendJson(res, status, { error: error instanceof Error ? error.message : String(error) })
|
|
735
985
|
}
|
|
736
986
|
}
|