forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlspPluginIntegration.ts
More file actions
387 lines (343 loc) · 12.1 KB
/
Copy pathlspPluginIntegration.ts
File metadata and controls
387 lines (343 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { readFile } from 'fs/promises'
import { join, relative, resolve } from 'path'
import { z } from 'zod/v4'
import type {
LspServerConfig,
ScopedLspServerConfig,
} from '../../services/lsp/types.js'
import { expandEnvVarsInString } from '../../services/mcp/envExpansion.js'
import type { LoadedPlugin, PluginError } from '../../types/plugin.js'
import { logForDebugging } from '../debug.js'
import { isENOENT, toError } from '../errors.js'
import { logError } from '../log.js'
import { jsonParse } from '../slowOperations.js'
import { getPluginDataDir } from './pluginDirectories.js'
import {
getPluginStorageId,
loadPluginOptions,
type PluginOptionValues,
substitutePluginVariables,
substituteUserConfigVariables,
} from './pluginOptionsStorage.js'
import { LspServerConfigSchema } from './schemas.js'
/**
* Validate that a resolved path stays within the plugin directory.
* Prevents path traversal attacks via .. or absolute paths.
*/
function validatePathWithinPlugin(
pluginPath: string,
relativePath: string,
): string | null {
// Resolve both paths to absolute paths
const resolvedPluginPath = resolve(pluginPath)
const resolvedFilePath = resolve(pluginPath, relativePath)
// Check if the resolved file path is within the plugin directory
const rel = relative(resolvedPluginPath, resolvedFilePath)
// If relative path starts with .. or is absolute, it's outside the plugin dir
if (rel.startsWith('..') || resolve(rel) === rel) {
return null
}
return resolvedFilePath
}
/**
* Load LSP server configurations from a plugin.
* Checks for:
* 1. .lsp.json file in plugin directory
* 2. manifest.lspServers field
*
* @param plugin - The loaded plugin
* @param errors - Array to collect any errors encountered
* @returns Record of server name to config, or undefined if no servers
*/
export async function loadPluginLspServers(
plugin: LoadedPlugin,
errors: PluginError[] = [],
): Promise<Record<string, LspServerConfig> | undefined> {
const servers: Record<string, LspServerConfig> = {}
// 1. Check for .lsp.json file in plugin directory
const lspJsonPath = join(plugin.path, '.lsp.json')
try {
const content = await readFile(lspJsonPath, 'utf-8')
const parsed = jsonParse(content)
const result = z
.record(z.string(), LspServerConfigSchema())
.safeParse(parsed)
if (result.success) {
Object.assign(servers, result.data)
} else {
const errorMsg = `LSP config validation failed for .lsp.json in plugin ${plugin.name}: ${result.error.message}`
logError(new Error(errorMsg))
errors.push({
type: 'lsp-config-invalid',
plugin: plugin.name,
serverName: '.lsp.json',
validationError: result.error.message,
source: 'plugin',
})
}
} catch (error) {
// .lsp.json is optional, ignore if it doesn't exist
if (!isENOENT(error)) {
const _errorMsg =
error instanceof Error
? `Failed to read/parse .lsp.json in plugin ${plugin.name}: ${error.message}`
: `Failed to read/parse .lsp.json file in plugin ${plugin.name}`
logError(toError(error))
errors.push({
type: 'lsp-config-invalid',
plugin: plugin.name,
serverName: '.lsp.json',
validationError:
error instanceof Error
? `Failed to parse JSON: ${error.message}`
: 'Failed to parse JSON file',
source: 'plugin',
})
}
}
// 2. Check manifest.lspServers field
if (plugin.manifest.lspServers) {
const manifestServers = await loadLspServersFromManifest(
plugin.manifest.lspServers,
plugin.path,
plugin.name,
errors,
)
if (manifestServers) {
Object.assign(servers, manifestServers)
}
}
return Object.keys(servers).length > 0 ? servers : undefined
}
/**
* Load LSP servers from manifest declaration (handles multiple formats).
*/
async function loadLspServersFromManifest(
declaration:
| string
| Record<string, LspServerConfig>
| Array<string | Record<string, LspServerConfig>>,
pluginPath: string,
pluginName: string,
errors: PluginError[],
): Promise<Record<string, LspServerConfig> | undefined> {
const servers: Record<string, LspServerConfig> = {}
// Normalize to array
const declarations = Array.isArray(declaration) ? declaration : [declaration]
for (const decl of declarations) {
if (typeof decl === 'string') {
// Validate path to prevent directory traversal
const validatedPath = validatePathWithinPlugin(pluginPath, decl)
if (!validatedPath) {
const securityMsg = `Security: Path traversal attempt blocked in plugin ${pluginName}: ${decl}`
logError(new Error(securityMsg))
logForDebugging(securityMsg, { level: 'warn' })
errors.push({
type: 'lsp-config-invalid',
plugin: pluginName,
serverName: decl,
validationError:
'Invalid path: must be relative and within plugin directory',
source: 'plugin',
})
continue
}
// Load from file
try {
const content = await readFile(validatedPath, 'utf-8')
const parsed = jsonParse(content)
const result = z
.record(z.string(), LspServerConfigSchema())
.safeParse(parsed)
if (result.success) {
Object.assign(servers, result.data)
} else {
const errorMsg = `LSP config validation failed for ${decl} in plugin ${pluginName}: ${result.error.message}`
logError(new Error(errorMsg))
errors.push({
type: 'lsp-config-invalid',
plugin: pluginName,
serverName: decl,
validationError: result.error.message,
source: 'plugin',
})
}
} catch (error) {
const _errorMsg =
error instanceof Error
? `Failed to read/parse LSP config from ${decl} in plugin ${pluginName}: ${error.message}`
: `Failed to read/parse LSP config file ${decl} in plugin ${pluginName}`
logError(toError(error))
errors.push({
type: 'lsp-config-invalid',
plugin: pluginName,
serverName: decl,
validationError:
error instanceof Error
? `Failed to parse JSON: ${error.message}`
: 'Failed to parse JSON file',
source: 'plugin',
})
}
} else {
// Inline configs
for (const [serverName, config] of Object.entries(decl)) {
const result = LspServerConfigSchema().safeParse(config)
if (result.success) {
servers[serverName] = result.data
} else {
const errorMsg = `LSP config validation failed for inline server "${serverName}" in plugin ${pluginName}: ${result.error.message}`
logError(new Error(errorMsg))
errors.push({
type: 'lsp-config-invalid',
plugin: pluginName,
serverName,
validationError: result.error.message,
source: 'plugin',
})
}
}
}
}
return Object.keys(servers).length > 0 ? servers : undefined
}
/**
* Resolve environment variables for plugin LSP servers.
* Handles ${CLAUDE_PLUGIN_ROOT}, ${user_config.X}, and general ${VAR}
* substitution. Tracks missing environment variables for error reporting.
*/
export function resolvePluginLspEnvironment(
config: LspServerConfig,
plugin: { path: string; source: string },
userConfig?: PluginOptionValues,
_errors?: PluginError[],
): LspServerConfig {
const allMissingVars: string[] = []
const resolveValue = (value: string): string => {
// First substitute plugin-specific variables
let resolved = substitutePluginVariables(value, plugin)
// Then substitute user config variables if provided
if (userConfig) {
resolved = substituteUserConfigVariables(resolved, userConfig)
}
// Finally expand general environment variables
const { expanded, missingVars } = expandEnvVarsInString(resolved)
allMissingVars.push(...missingVars)
return expanded
}
const resolved = { ...config }
// Resolve command path
if (resolved.command) {
resolved.command = resolveValue(resolved.command)
}
// Resolve args
if (resolved.args) {
resolved.args = resolved.args.map(arg => resolveValue(arg))
}
// Resolve environment variables and add CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA
const resolvedEnv: Record<string, string> = {
CLAUDE_PLUGIN_ROOT: plugin.path,
CLAUDE_PLUGIN_DATA: getPluginDataDir(plugin.source),
...(resolved.env || {}),
}
for (const [key, value] of Object.entries(resolvedEnv)) {
if (key !== 'CLAUDE_PLUGIN_ROOT' && key !== 'CLAUDE_PLUGIN_DATA') {
resolvedEnv[key] = resolveValue(value)
}
}
resolved.env = resolvedEnv
// Resolve workspaceFolder if present
if (resolved.workspaceFolder) {
resolved.workspaceFolder = resolveValue(resolved.workspaceFolder)
}
// Log missing variables if any were found
if (allMissingVars.length > 0) {
const uniqueMissingVars = [...new Set(allMissingVars)]
const warnMsg = `Missing environment variables in plugin LSP config: ${uniqueMissingVars.join(', ')}`
logError(new Error(warnMsg))
logForDebugging(warnMsg, { level: 'warn' })
}
return resolved
}
/**
* Add plugin scope to LSP server configs
* This adds a prefix to server names to avoid conflicts between plugins
*/
export function addPluginScopeToLspServers(
servers: Record<string, LspServerConfig>,
pluginName: string,
): Record<string, ScopedLspServerConfig> {
const scopedServers: Record<string, ScopedLspServerConfig> = {}
for (const [name, config] of Object.entries(servers)) {
// Add plugin prefix to server name to avoid conflicts
const scopedName = `plugin:${pluginName}:${name}`
scopedServers[scopedName] = {
...config,
scope: 'dynamic', // Use dynamic scope for plugin servers
source: pluginName,
}
}
return scopedServers
}
/**
* Get LSP servers from a specific plugin with environment variable resolution and scoping
* This function is called when the LSP servers need to be activated and ensures they have
* the proper environment variables and scope applied
*/
export async function getPluginLspServers(
plugin: LoadedPlugin,
errors: PluginError[] = [],
): Promise<Record<string, ScopedLspServerConfig> | undefined> {
if (!plugin.enabled) {
return undefined
}
// Use cached servers if available
const servers =
plugin.lspServers || (await loadPluginLspServers(plugin, errors))
if (!servers) {
return undefined
}
// Resolve environment variables. Top-level manifest.userConfig values
// become available as ${user_config.KEY} in LSP command/args/env.
// Gate on manifest.userConfig — same rationale as buildMcpUserConfig:
// loadPluginOptions always returns {} so without this guard userConfig is
// truthy for every plugin and substituteUserConfigVariables throws on any
// unresolved ${user_config.X}. Also skips unneeded keychain reads.
const userConfig = plugin.manifest.userConfig
? loadPluginOptions(getPluginStorageId(plugin))
: undefined
const resolvedServers: Record<string, LspServerConfig> = {}
for (const [name, config] of Object.entries(servers)) {
resolvedServers[name] = resolvePluginLspEnvironment(
config,
plugin,
userConfig,
errors,
)
}
// Add plugin scope
return addPluginScopeToLspServers(resolvedServers, plugin.name)
}
/**
* Extract all LSP servers from loaded plugins
*/
export async function extractLspServersFromPlugins(
plugins: LoadedPlugin[],
errors: PluginError[] = [],
): Promise<Record<string, ScopedLspServerConfig>> {
const allServers: Record<string, ScopedLspServerConfig> = {}
for (const plugin of plugins) {
if (!plugin.enabled) continue
const servers = await loadPluginLspServers(plugin, errors)
if (servers) {
const scopedServers = addPluginScopeToLspServers(servers, plugin.name)
Object.assign(allServers, scopedServers)
// Store the servers on the plugin for caching
plugin.lspServers = servers
logForDebugging(
`Loaded ${Object.keys(servers).length} LSP servers from plugin ${plugin.name}`,
)
}
}
return allServers
}