@shieldaai/security-watch 1.3.0 → 1.4.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/CHANGELOG.md +21 -0
- package/CONTRIBUTING.md +2 -0
- package/README.md +68 -42
- package/dist/check.d.ts +193 -0
- package/dist/check.js +1000 -0
- package/dist/cli.js +115 -2
- package/dist/inventory.d.ts +2 -1
- package/dist/inventory.js +1 -2
- package/dist/manifests.d.ts +7 -0
- package/dist/manifests.js +16 -0
- package/dist/mcp-server.d.ts +256 -0
- package/dist/mcp-server.js +755 -0
- package/dist/sources.d.ts +2 -0
- package/dist/sources.js +4 -0
- package/docs/agents.md +139 -0
- package/docs/offline-advisory-preview.md +2 -2
- package/docs/sbom.md +3 -3
- package/npm-shrinkwrap.json +237 -0
- package/package.json +10 -5
|
@@ -0,0 +1,755 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { cachingHttp, checkAdvisory, checkChange, checkPackages, checkProject, formatAdvisoryReport, formatChangeReport, formatCheckReport, isUnreadableWarning, } from './check.js';
|
|
8
|
+
import { loadConfig } from './config.js';
|
|
9
|
+
import { generateSbom } from './manifests.js';
|
|
10
|
+
import { maxAges, withCurrentMitigations } from './mitigations.js';
|
|
11
|
+
import { Store } from './store.js';
|
|
12
|
+
import { cleanText } from './util.js';
|
|
13
|
+
/**
|
|
14
|
+
* A Model Context Protocol server (stdio, newline-delimited JSON-RPC) that gives AI agents
|
|
15
|
+
* Security Watch's checks for the project they have open. It reads files under one project root
|
|
16
|
+
* and never outside it, never runs project code, writes only when `write_sbom` is called, and sends
|
|
17
|
+
* package names and versions to OSV (plus CVE IDs to FIRST when EPSS is asked for).
|
|
18
|
+
*/
|
|
19
|
+
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
20
|
+
const MAX_LINE = 4 * 1024 * 1024;
|
|
21
|
+
const MAX_TEXT = 60_000;
|
|
22
|
+
const SEVERITIES = ['critical', 'high', 'medium', 'low'];
|
|
23
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
24
|
+
const network = 'Sends package names and versions (never file contents) to OSV (api.osv.dev) and reads the CISA known-exploited catalog.';
|
|
25
|
+
const pathProperty = {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'A folder or one dependency file inside the project, relative to its root. Default: the whole project.',
|
|
28
|
+
};
|
|
29
|
+
const minSeverity = {
|
|
30
|
+
type: 'string',
|
|
31
|
+
enum: [...SEVERITIES],
|
|
32
|
+
description: 'Leave out findings below this priority. Malware and known-exploited findings are always shown; an advisory without a severity counts as medium. Default: low.',
|
|
33
|
+
};
|
|
34
|
+
const production = {
|
|
35
|
+
type: 'boolean',
|
|
36
|
+
description: 'Leave out development-only dependencies where the lockfile marks them. Default: false.',
|
|
37
|
+
};
|
|
38
|
+
const epss = {
|
|
39
|
+
type: 'boolean',
|
|
40
|
+
description: 'Add FIRST EPSS exploit-probability scores (sends CVE IDs to api.first.org). Default: false.',
|
|
41
|
+
};
|
|
42
|
+
export const TOOLS = [
|
|
43
|
+
{
|
|
44
|
+
name: 'check_project_vulnerabilities',
|
|
45
|
+
title: 'Check project dependencies for known vulnerabilities',
|
|
46
|
+
description: `Reads every lockfile and manifest in the project (npm, Python, Go, Rust, PHP, Ruby, Java, .NET, Dart, Elixir, Swift, Haskell) and lists known vulnerabilities and malicious packages in the installed versions, most urgent first, each with the fixed version and the file to change. ${network}`,
|
|
47
|
+
inputSchema: {
|
|
48
|
+
type: 'object',
|
|
49
|
+
properties: {
|
|
50
|
+
path: pathProperty,
|
|
51
|
+
sbom: {
|
|
52
|
+
type: 'string',
|
|
53
|
+
description: 'A CycloneDX or SPDX JSON SBOM inside the project (from Trivy, Syft, cdxgen, GitHub) to check instead of the dependency files.',
|
|
54
|
+
},
|
|
55
|
+
minSeverity,
|
|
56
|
+
production,
|
|
57
|
+
epss,
|
|
58
|
+
},
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
},
|
|
61
|
+
annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true, destructiveHint: false },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'check_dependency_change',
|
|
65
|
+
title: 'Check what a dependency change brings in',
|
|
66
|
+
description: `Compares the project's dependency files at a git ref with the working tree (tracked files and untracked ones that are not ignored) and reports only the known vulnerabilities the change adds, and those it fixes. Use it after adding, removing or upgrading dependencies, before you hand the change back. Reads the base files from git; checks nothing out. ${network}`,
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
base: {
|
|
71
|
+
type: 'string',
|
|
72
|
+
description: 'The git ref to compare with. HEAD for uncommitted changes. For a branch, the branch it merges into with three dots, such as origin/main..., compares with the point where the branch left it (plain origin/main would also count what main changed since). After committing, HEAD shows nothing: use HEAD~1 or origin/main....',
|
|
73
|
+
},
|
|
74
|
+
path: {
|
|
75
|
+
...pathProperty,
|
|
76
|
+
description: 'A folder inside the project, relative to its root. Default: the whole project.',
|
|
77
|
+
},
|
|
78
|
+
minSeverity,
|
|
79
|
+
production,
|
|
80
|
+
},
|
|
81
|
+
required: ['base'],
|
|
82
|
+
additionalProperties: false,
|
|
83
|
+
},
|
|
84
|
+
annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true, destructiveHint: false },
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: 'check_package',
|
|
88
|
+
title: 'Check packages before adding or upgrading them',
|
|
89
|
+
description: `Checks named package versions against OSV before you add or upgrade them: known vulnerabilities, malicious-package records (typosquats, hijacked releases) and the versions that fix each. Leave out the version to list every advisory for the package. OSV does not say whether a package exists: confirm an unfamiliar name in its registry. ${network}`,
|
|
90
|
+
inputSchema: {
|
|
91
|
+
type: 'object',
|
|
92
|
+
properties: {
|
|
93
|
+
packages: {
|
|
94
|
+
type: 'array',
|
|
95
|
+
minItems: 1,
|
|
96
|
+
maxItems: 50,
|
|
97
|
+
items: {
|
|
98
|
+
type: 'object',
|
|
99
|
+
properties: {
|
|
100
|
+
ecosystem: {
|
|
101
|
+
type: 'string',
|
|
102
|
+
description: 'npm, PyPI, Go, crates.io, Packagist, RubyGems, Maven, NuGet, Pub, Hex, SwiftURL or Hackage (python, rust, php, ruby, java, dotnet, dart and elixir also work).',
|
|
103
|
+
},
|
|
104
|
+
name: {
|
|
105
|
+
type: 'string',
|
|
106
|
+
description: 'The package name as the registry spells it, such as lodash, @scope/pkg, requests or org.apache.logging.log4j:log4j-core.',
|
|
107
|
+
},
|
|
108
|
+
version: { type: 'string', description: 'The exact version, such as 4.17.21.' },
|
|
109
|
+
},
|
|
110
|
+
required: ['ecosystem', 'name'],
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
epss,
|
|
115
|
+
},
|
|
116
|
+
required: ['packages'],
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
},
|
|
119
|
+
annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true, destructiveHint: false },
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
name: 'check_advisory',
|
|
123
|
+
title: 'Does this advisory affect the project?',
|
|
124
|
+
description: `Looks up a CVE, GHSA, PYSEC, RUSTSEC, GO, MAL or other OSV identifier, says which packages and versions it concerns and whether this project has an affected version. Use it when someone asks whether a vulnerability in the news concerns them. ${network}`,
|
|
125
|
+
inputSchema: {
|
|
126
|
+
type: 'object',
|
|
127
|
+
properties: {
|
|
128
|
+
id: {
|
|
129
|
+
type: 'string',
|
|
130
|
+
description: 'The advisory ID, such as CVE-2021-44906 or GHSA-xvch-5gv4-984h.',
|
|
131
|
+
},
|
|
132
|
+
path: pathProperty,
|
|
133
|
+
},
|
|
134
|
+
required: ['id'],
|
|
135
|
+
additionalProperties: false,
|
|
136
|
+
},
|
|
137
|
+
annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true, destructiveHint: false },
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: 'list_dependencies',
|
|
141
|
+
title: 'List the project dependencies',
|
|
142
|
+
description: 'Lists the dependency files found in the project, package counts per ecosystem, packages that have no exact version (a manifest without its lockfile) and files that could not be read. Optionally lists every package. Reads files only; no network.',
|
|
143
|
+
inputSchema: {
|
|
144
|
+
type: 'object',
|
|
145
|
+
properties: {
|
|
146
|
+
path: pathProperty,
|
|
147
|
+
production,
|
|
148
|
+
includePackages: {
|
|
149
|
+
type: 'boolean',
|
|
150
|
+
description: 'Also list every package and version (up to 2,000). Default: false.',
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
additionalProperties: false,
|
|
154
|
+
},
|
|
155
|
+
annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true, destructiveHint: false },
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
name: 'write_sbom',
|
|
159
|
+
title: 'Write a CycloneDX SBOM',
|
|
160
|
+
description: 'Writes a CycloneDX 1.6 JSON SBOM of the project dependencies to a new file inside the project, for a customer, a compliance request (such as the EU Cyber Resilience Act), Dependency-Track, Trivy or a Security Watch monitor. It replaces an existing file only with overwrite: true, and only when that file is itself an SBOM; it never writes into hidden folders such as .github or .claude. No network.',
|
|
161
|
+
inputSchema: {
|
|
162
|
+
type: 'object',
|
|
163
|
+
properties: {
|
|
164
|
+
output: {
|
|
165
|
+
type: 'string',
|
|
166
|
+
description: 'Where to write it, relative to the project root, ending in .json, such as sbom.cdx.json.',
|
|
167
|
+
},
|
|
168
|
+
path: pathProperty,
|
|
169
|
+
production,
|
|
170
|
+
name: {
|
|
171
|
+
type: 'string',
|
|
172
|
+
description: 'System name written into the SBOM. Default: the name in package.json or pyproject.toml, or the folder name.',
|
|
173
|
+
},
|
|
174
|
+
owner: {
|
|
175
|
+
type: 'string',
|
|
176
|
+
description: 'Who to ask about this system, such as "Dana, platform team".',
|
|
177
|
+
},
|
|
178
|
+
environment: { type: 'string', description: 'Such as production or staging.' },
|
|
179
|
+
note: { type: 'string', description: 'Where the system runs; Security Watch shows it in alerts.' },
|
|
180
|
+
exposure: { type: 'string', enum: ['internet', 'internal', 'unknown'] },
|
|
181
|
+
overwrite: {
|
|
182
|
+
type: 'boolean',
|
|
183
|
+
description: 'Replace the file if it exists and is a CycloneDX or SPDX SBOM. Default: false.',
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
required: ['output'],
|
|
187
|
+
additionalProperties: false,
|
|
188
|
+
},
|
|
189
|
+
// destructiveHint: with overwrite it replaces an existing SBOM file.
|
|
190
|
+
annotations: { readOnlyHint: false, openWorldHint: false, idempotentHint: true, destructiveHint: true },
|
|
191
|
+
},
|
|
192
|
+
];
|
|
193
|
+
const WATCH_TOOL = {
|
|
194
|
+
name: 'list_watch_findings',
|
|
195
|
+
title: 'List open findings from the Security Watch monitor',
|
|
196
|
+
description: 'Lists the open findings recorded by the Security Watch monitor this server is configured with (SECURITY_WATCH_CONFIG): what affects which system, its priority, the fix and where to look. Reads the monitor database only; changes nothing and makes no network requests.',
|
|
197
|
+
inputSchema: {
|
|
198
|
+
type: 'object',
|
|
199
|
+
properties: {
|
|
200
|
+
minSeverity,
|
|
201
|
+
system: { type: 'string', description: 'Only this system ID.' },
|
|
202
|
+
limit: {
|
|
203
|
+
type: 'integer',
|
|
204
|
+
minimum: 1,
|
|
205
|
+
maximum: 200,
|
|
206
|
+
description: 'At most this many findings. Default: 50.',
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
additionalProperties: false,
|
|
210
|
+
},
|
|
211
|
+
annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true, destructiveHint: false },
|
|
212
|
+
};
|
|
213
|
+
function real(path) {
|
|
214
|
+
try {
|
|
215
|
+
return realpathSync(path);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return resolve(path);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function isInside(child, parent) {
|
|
222
|
+
const rel = relative(parent, child);
|
|
223
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
224
|
+
}
|
|
225
|
+
/** A folder can be a project root unless it is a filesystem root, the home folder or above it. */
|
|
226
|
+
export function usableRoot(candidate, home = homedir()) {
|
|
227
|
+
const root = real(candidate);
|
|
228
|
+
if (root === parse(root).root)
|
|
229
|
+
return false;
|
|
230
|
+
if (home && isInside(real(home), root))
|
|
231
|
+
return false;
|
|
232
|
+
try {
|
|
233
|
+
return statSync(root).isDirectory();
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
class ToolError extends Error {
|
|
240
|
+
}
|
|
241
|
+
export class SecurityWatchMcpServer {
|
|
242
|
+
#root;
|
|
243
|
+
#rootFromClient = false;
|
|
244
|
+
#config;
|
|
245
|
+
#http;
|
|
246
|
+
#home;
|
|
247
|
+
#now;
|
|
248
|
+
#send;
|
|
249
|
+
#pending = new Map();
|
|
250
|
+
#running = new Map();
|
|
251
|
+
#clientRoots = false;
|
|
252
|
+
/** The client's answer to roots/list, while it is outstanding: tool calls wait for it. */
|
|
253
|
+
#rootsPending;
|
|
254
|
+
#nextId = 1;
|
|
255
|
+
constructor(options, send) {
|
|
256
|
+
this.#home = options.home ?? homedir();
|
|
257
|
+
this.#root = options.root && usableRoot(options.root, this.#home) ? real(options.root) : undefined;
|
|
258
|
+
this.#config = options.config;
|
|
259
|
+
this.#http = options.http ?? cachingHttp();
|
|
260
|
+
this.#now = options.now ?? Date.now;
|
|
261
|
+
this.#send = send;
|
|
262
|
+
}
|
|
263
|
+
get root() {
|
|
264
|
+
return this.#root;
|
|
265
|
+
}
|
|
266
|
+
tools() {
|
|
267
|
+
return [...TOOLS, ...(this.#config ? [WATCH_TOOL] : [])];
|
|
268
|
+
}
|
|
269
|
+
/** Handles one message from the client. Responses go through `send`. */
|
|
270
|
+
async handle(raw) {
|
|
271
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
272
|
+
this.#send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
const message = raw;
|
|
276
|
+
// A response to a request this server sent (roots/list).
|
|
277
|
+
if (message.method === undefined && message.id !== undefined && message.id !== null) {
|
|
278
|
+
const resolveReply = this.#pending.get(String(message.id));
|
|
279
|
+
if (resolveReply) {
|
|
280
|
+
this.#pending.delete(String(message.id));
|
|
281
|
+
resolveReply(message);
|
|
282
|
+
}
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (typeof message.method !== 'string') {
|
|
286
|
+
this.#send({
|
|
287
|
+
jsonrpc: '2.0',
|
|
288
|
+
id: message.id ?? null,
|
|
289
|
+
error: { code: -32600, message: 'Invalid request' },
|
|
290
|
+
});
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const params = (typeof message.params === 'object' && message.params !== null ? message.params : {});
|
|
294
|
+
if (message.id === undefined || message.id === null) {
|
|
295
|
+
this.#notification(message.method, params);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const id = message.id;
|
|
299
|
+
const reply = (result) => this.#send({ jsonrpc: '2.0', id, result });
|
|
300
|
+
const fail = (code, text) => this.#send({ jsonrpc: '2.0', id, error: { code, message: text } });
|
|
301
|
+
switch (message.method) {
|
|
302
|
+
case 'initialize': {
|
|
303
|
+
const asked = typeof params.protocolVersion === 'string' ? params.protocolVersion : '';
|
|
304
|
+
const capabilities = (params.capabilities ?? {});
|
|
305
|
+
this.#clientRoots = typeof capabilities.roots === 'object' && capabilities.roots !== null;
|
|
306
|
+
reply({
|
|
307
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
308
|
+
capabilities: { tools: { listChanged: false } },
|
|
309
|
+
serverInfo: { name: 'security-watch', title: 'Shielda Security Watch', version: VERSION },
|
|
310
|
+
instructions: 'Security Watch checks the dependencies of the open project for known vulnerabilities and malicious packages. ' +
|
|
311
|
+
'Call check_package before adding or upgrading a dependency, check_dependency_change (base "HEAD") after changing dependency files and before handing the change back, ' +
|
|
312
|
+
'check_project_vulnerabilities for an overview, and check_advisory when asked whether a CVE or GHSA affects the project. ' +
|
|
313
|
+
'Findings come from OSV and CISA KEV as of now; a clean result means no known advisory, not that the code is safe.',
|
|
314
|
+
});
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
case 'ping':
|
|
318
|
+
reply({});
|
|
319
|
+
return;
|
|
320
|
+
case 'tools/list':
|
|
321
|
+
reply({ tools: this.tools() });
|
|
322
|
+
return;
|
|
323
|
+
case 'tools/call': {
|
|
324
|
+
const controller = new AbortController();
|
|
325
|
+
this.#running.set(id, controller);
|
|
326
|
+
try {
|
|
327
|
+
// A call that arrives right after start-up waits for the client to name the project.
|
|
328
|
+
if (!this.#root && this.#rootsPending)
|
|
329
|
+
await this.#rootsPending;
|
|
330
|
+
const text = await this.#call(String(params.name ?? ''), this.#arguments(params.arguments), controller.signal);
|
|
331
|
+
if (!controller.signal.aborted)
|
|
332
|
+
reply({ content: [{ type: 'text', text: clip(text) }], isError: false });
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
if (controller.signal.aborted)
|
|
336
|
+
return;
|
|
337
|
+
if (error instanceof UnknownTool)
|
|
338
|
+
fail(-32602, error.message);
|
|
339
|
+
else
|
|
340
|
+
reply({
|
|
341
|
+
content: [
|
|
342
|
+
{
|
|
343
|
+
type: 'text',
|
|
344
|
+
text: error instanceof Error ? cleanText(error.message, 1000) : 'The check failed.',
|
|
345
|
+
},
|
|
346
|
+
],
|
|
347
|
+
isError: true,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
finally {
|
|
351
|
+
this.#running.delete(id);
|
|
352
|
+
}
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
default:
|
|
356
|
+
fail(-32601, `Method not found: ${message.method}`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
#notification(method, params) {
|
|
360
|
+
if (method === 'notifications/initialized' || method === 'notifications/roots/list_changed') {
|
|
361
|
+
if (this.#clientRoots && (!this.#root || this.#rootFromClient))
|
|
362
|
+
this.#rootsPending = this.#askRoots();
|
|
363
|
+
}
|
|
364
|
+
else if (method === 'notifications/cancelled') {
|
|
365
|
+
const requestId = params.requestId;
|
|
366
|
+
if (requestId !== undefined)
|
|
367
|
+
this.#running.get(requestId)?.abort();
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async #askRoots() {
|
|
371
|
+
const id = `security-watch-roots-${this.#nextId++}`;
|
|
372
|
+
const answer = new Promise((done) => {
|
|
373
|
+
this.#pending.set(id, done);
|
|
374
|
+
setTimeout(() => {
|
|
375
|
+
if (this.#pending.delete(id))
|
|
376
|
+
done({ error: 'timeout' });
|
|
377
|
+
}, 10_000).unref();
|
|
378
|
+
});
|
|
379
|
+
this.#send({ jsonrpc: '2.0', id, method: 'roots/list', params: {} });
|
|
380
|
+
const message = await answer;
|
|
381
|
+
const roots = message.result?.roots ?? [];
|
|
382
|
+
for (const root of roots) {
|
|
383
|
+
if (typeof root.uri !== 'string' || !root.uri.startsWith('file://'))
|
|
384
|
+
continue;
|
|
385
|
+
let path;
|
|
386
|
+
try {
|
|
387
|
+
path = fileURLToPath(root.uri);
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (usableRoot(path, this.#home)) {
|
|
393
|
+
this.#root = real(path);
|
|
394
|
+
this.#rootFromClient = true;
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
#arguments(value) {
|
|
400
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
401
|
+
? value
|
|
402
|
+
: {};
|
|
403
|
+
}
|
|
404
|
+
#project() {
|
|
405
|
+
if (!this.#root)
|
|
406
|
+
throw new ToolError('No project folder is open: the server was started outside a project and the client named none. Restart it with the project path as its argument (security-watch mcp /path/to/project).');
|
|
407
|
+
return this.#root;
|
|
408
|
+
}
|
|
409
|
+
/** A path inside the project: no `..` out of it and no symbolic link that leads out. */
|
|
410
|
+
#inside(path, what = 'path') {
|
|
411
|
+
const root = this.#project();
|
|
412
|
+
if (path === undefined || path === '' || path === '.')
|
|
413
|
+
return root;
|
|
414
|
+
if (typeof path !== 'string' || path.includes('\0'))
|
|
415
|
+
throw new ToolError(`${what} must be a path inside the project.`);
|
|
416
|
+
const absolute = resolve(root, path);
|
|
417
|
+
if (!isInside(absolute, root) || !isInside(real(absolute), root))
|
|
418
|
+
throw new ToolError(`${what} must be inside the project (${root}).`);
|
|
419
|
+
if (!existsSync(absolute))
|
|
420
|
+
throw new ToolError(`${path} does not exist in the project.`);
|
|
421
|
+
return real(absolute);
|
|
422
|
+
}
|
|
423
|
+
#options(signal, args) {
|
|
424
|
+
return { http: this.#http, now: this.#now(), signal, ...(args.epss === true ? { epss: true } : {}) };
|
|
425
|
+
}
|
|
426
|
+
async #call(name, args, signal) {
|
|
427
|
+
const min = severity(args.minSeverity);
|
|
428
|
+
const prod = args.production === true ? { production: true } : {};
|
|
429
|
+
switch (name) {
|
|
430
|
+
case 'check_project_vulnerabilities': {
|
|
431
|
+
if (args.sbom !== undefined && args.path !== undefined)
|
|
432
|
+
throw new ToolError('Give path or sbom, not both.');
|
|
433
|
+
const sbom = args.sbom === undefined ? undefined : this.#inside(args.sbom, 'sbom');
|
|
434
|
+
if (sbom && !statSync(sbom).isFile())
|
|
435
|
+
throw new ToolError('sbom must be a JSON file.');
|
|
436
|
+
const report = await checkProject({
|
|
437
|
+
...this.#options(signal, args),
|
|
438
|
+
...(sbom ? { sbom } : { project: this.#inside(args.path) }),
|
|
439
|
+
...prod,
|
|
440
|
+
});
|
|
441
|
+
return formatCheckReport(report, min);
|
|
442
|
+
}
|
|
443
|
+
case 'check_dependency_change': {
|
|
444
|
+
if (typeof args.base !== 'string' || !args.base.trim())
|
|
445
|
+
throw new ToolError('base is required, such as "HEAD".');
|
|
446
|
+
const project = this.#inside(args.path);
|
|
447
|
+
if (!statSync(project).isDirectory())
|
|
448
|
+
throw new ToolError('path must be a folder for a change check.');
|
|
449
|
+
const report = await checkChange({
|
|
450
|
+
...this.#options(signal, args),
|
|
451
|
+
project,
|
|
452
|
+
base: args.base.trim(),
|
|
453
|
+
...prod,
|
|
454
|
+
});
|
|
455
|
+
return formatChangeReport(report, min);
|
|
456
|
+
}
|
|
457
|
+
case 'check_package': {
|
|
458
|
+
if (!Array.isArray(args.packages) || !args.packages.length)
|
|
459
|
+
throw new ToolError('packages must list at least one package.');
|
|
460
|
+
if (args.packages.length > 50)
|
|
461
|
+
throw new ToolError('Check at most 50 packages at a time.');
|
|
462
|
+
const packages = args.packages.map((item) => {
|
|
463
|
+
const value = this.#arguments(item);
|
|
464
|
+
if (typeof value.ecosystem !== 'string' || typeof value.name !== 'string')
|
|
465
|
+
throw new ToolError('Each package needs an ecosystem and a name.');
|
|
466
|
+
return {
|
|
467
|
+
ecosystem: value.ecosystem,
|
|
468
|
+
name: value.name,
|
|
469
|
+
...(typeof value.version === 'string' && value.version.trim() ? { version: value.version } : {}),
|
|
470
|
+
};
|
|
471
|
+
});
|
|
472
|
+
const report = await checkPackages(packages, this.#options(signal, args));
|
|
473
|
+
const text = formatCheckReport(report);
|
|
474
|
+
const unversioned = packages.filter((item) => !item.version).length;
|
|
475
|
+
return unversioned
|
|
476
|
+
? `${text}\n\nWithout a version every advisory for the package is listed; give the version you plan to install to see only what affects it.`
|
|
477
|
+
: text;
|
|
478
|
+
}
|
|
479
|
+
case 'check_advisory': {
|
|
480
|
+
if (typeof args.id !== 'string' || !args.id.trim())
|
|
481
|
+
throw new ToolError('id is required, such as CVE-2021-44906.');
|
|
482
|
+
const report = await checkAdvisory(args.id, {
|
|
483
|
+
...this.#options(signal, args),
|
|
484
|
+
project: this.#inside(args.path),
|
|
485
|
+
});
|
|
486
|
+
return formatAdvisoryReport(report);
|
|
487
|
+
}
|
|
488
|
+
case 'list_dependencies':
|
|
489
|
+
return this.#dependencies(args);
|
|
490
|
+
case 'write_sbom':
|
|
491
|
+
return this.#writeSbom(args);
|
|
492
|
+
case 'list_watch_findings':
|
|
493
|
+
if (this.#config)
|
|
494
|
+
return this.#watchFindings(args, min);
|
|
495
|
+
throw new UnknownTool(`Unknown tool ${name}`);
|
|
496
|
+
default:
|
|
497
|
+
throw new UnknownTool(`Unknown tool ${name}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
#dependencies(args) {
|
|
501
|
+
const project = this.#inside(args.path);
|
|
502
|
+
let result;
|
|
503
|
+
try {
|
|
504
|
+
result = generateSbom({ project, ...(args.production === true ? { production: true } : {}) });
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
throw new ToolError(error instanceof Error ? error.message : 'Could not read the project.');
|
|
508
|
+
}
|
|
509
|
+
const files = result.files.filter((file) => file.packages);
|
|
510
|
+
const out = [
|
|
511
|
+
`${result.packages} package${result.packages === 1 ? '' : 's'}${result.ecosystems.length ? ` (${result.ecosystems.join(', ')})` : ''} from ${files.length} file${files.length === 1 ? '' : 's'}:`,
|
|
512
|
+
...files.map((file) => `- ${file.path}: ${file.ecosystem} ${file.kind}, ${file.packages} package${file.packages === 1 ? '' : 's'}`),
|
|
513
|
+
];
|
|
514
|
+
const components = (result.bom.components ?? []);
|
|
515
|
+
const unversioned = components.filter((component) => !component.version);
|
|
516
|
+
if (unversioned.length)
|
|
517
|
+
out.push('', `${unversioned.length} without an exact version (add or commit the lockfile so checks can compare versions): ${unversioned
|
|
518
|
+
.slice(0, 30)
|
|
519
|
+
.map((component) => component.purl ?? component.name)
|
|
520
|
+
.join(', ')}${unversioned.length > 30 ? `, and ${unversioned.length - 30} more` : ''}`);
|
|
521
|
+
const unreadable = result.warnings.filter(isUnreadableWarning);
|
|
522
|
+
const notes = result.warnings.filter((warning) => !isUnreadableWarning(warning));
|
|
523
|
+
if (unreadable.length)
|
|
524
|
+
out.push('', 'Could not be read (their packages are missing):', ...unreadable.slice(0, 20).map((warning) => `- ${warning}`));
|
|
525
|
+
if (notes.length)
|
|
526
|
+
out.push('', 'Notes:', ...notes.slice(0, 20).map((warning) => `- ${warning}`));
|
|
527
|
+
if (args.includePackages === true)
|
|
528
|
+
out.push('', 'Packages:', ...components
|
|
529
|
+
.slice(0, 2_000)
|
|
530
|
+
.map((component) => `- ${component.purl ?? `${component.group ? `${component.group}/` : ''}${component.name}@${component.version ?? '?'}`}`), ...(components.length > 2_000 ? [`- and ${components.length - 2_000} more`] : []));
|
|
531
|
+
return out.join('\n');
|
|
532
|
+
}
|
|
533
|
+
#writeSbom(args) {
|
|
534
|
+
const root = this.#project();
|
|
535
|
+
if (typeof args.output !== 'string' || !/\.json$/i.test(args.output))
|
|
536
|
+
throw new ToolError('output must be a path inside the project ending in .json, such as sbom.cdx.json.');
|
|
537
|
+
const destination = resolve(root, args.output);
|
|
538
|
+
if (!isInside(destination, root))
|
|
539
|
+
throw new ToolError(`output must be inside the project (${root}).`);
|
|
540
|
+
// Hidden folders hold settings (.github, .claude, .vscode, .git), never an SBOM.
|
|
541
|
+
if (relative(root, destination)
|
|
542
|
+
.split(/[\\/]/)
|
|
543
|
+
.some((part) => part.startsWith('.')))
|
|
544
|
+
throw new ToolError('output must not be in a hidden folder or be a hidden file.');
|
|
545
|
+
// The nearest folder that exists must be inside the project after links are followed, before
|
|
546
|
+
// anything is created: a link inside the project can point outside it.
|
|
547
|
+
let ancestor = dirname(destination);
|
|
548
|
+
while (!existsSync(ancestor) && isInside(dirname(ancestor), root) && dirname(ancestor) !== ancestor)
|
|
549
|
+
ancestor = dirname(ancestor);
|
|
550
|
+
if (!isInside(real(ancestor), root))
|
|
551
|
+
throw new ToolError(`output must be inside the project (${root}).`);
|
|
552
|
+
let existing;
|
|
553
|
+
try {
|
|
554
|
+
existing = lstatSync(destination); // also a link that points nowhere
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
existing = undefined;
|
|
558
|
+
}
|
|
559
|
+
if (existing) {
|
|
560
|
+
if (existing.isSymbolicLink() || !existing.isFile())
|
|
561
|
+
throw new ToolError('output exists and is not a plain file; name a new file.');
|
|
562
|
+
if (args.overwrite !== true)
|
|
563
|
+
throw new ToolError(`${args.output} exists. Pass overwrite: true to replace it, if it is an older SBOM.`);
|
|
564
|
+
if (!isSbomFile(destination))
|
|
565
|
+
throw new ToolError(`${args.output} exists and is not a CycloneDX or SPDX SBOM, so it is not replaced. Name a new file.`);
|
|
566
|
+
}
|
|
567
|
+
const project = this.#inside(args.path);
|
|
568
|
+
const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
|
|
569
|
+
const exposure = ['internet', 'internal', 'unknown'].includes(String(args.exposure))
|
|
570
|
+
? args.exposure
|
|
571
|
+
: undefined;
|
|
572
|
+
let result;
|
|
573
|
+
try {
|
|
574
|
+
result = generateSbom({
|
|
575
|
+
project,
|
|
576
|
+
toolVersion: VERSION,
|
|
577
|
+
...(args.production === true ? { production: true } : {}),
|
|
578
|
+
...(text(args.name) ? { name: text(args.name) } : {}),
|
|
579
|
+
...(text(args.owner) ? { owner: text(args.owner) } : {}),
|
|
580
|
+
...(text(args.environment) ? { environment: text(args.environment) } : {}),
|
|
581
|
+
...(text(args.note) ? { note: text(args.note) } : {}),
|
|
582
|
+
...(exposure ? { exposure } : {}),
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
throw new ToolError(error instanceof Error ? error.message : 'Could not read the project.');
|
|
587
|
+
}
|
|
588
|
+
if (!result.packages)
|
|
589
|
+
throw new ToolError('No dependencies found, so no SBOM was written.');
|
|
590
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
591
|
+
if (!isInside(real(dirname(destination)), root))
|
|
592
|
+
throw new ToolError(`output must be inside the project (${root}).`);
|
|
593
|
+
// Written beside the destination and renamed, so a reader never sees half a file.
|
|
594
|
+
const staging = mkdtempSync(join(dirname(destination), '.security-watch-'));
|
|
595
|
+
try {
|
|
596
|
+
const staged = join(staging, 'sbom.json');
|
|
597
|
+
writeFileSync(staged, `${JSON.stringify(result.bom, null, 2)}\n`, { flag: 'wx' });
|
|
598
|
+
renameSync(staged, destination);
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
rmSync(staging, { recursive: true, force: true });
|
|
602
|
+
}
|
|
603
|
+
const files = result.files.filter((file) => file.packages);
|
|
604
|
+
return [
|
|
605
|
+
`Wrote ${relative(root, destination) || basename(destination)}: CycloneDX 1.6, system "${result.system.name}" (ID ${result.system.id}), ${result.packages} package${result.packages === 1 ? '' : 's'} (${result.ecosystems.join(', ')}) from ${files.length} file${files.length === 1 ? '' : 's'}.`,
|
|
606
|
+
...(result.unversioned
|
|
607
|
+
? [`${result.unversioned} package${result.unversioned === 1 ? ' has' : 's have'} no exact version.`]
|
|
608
|
+
: []),
|
|
609
|
+
...result.warnings
|
|
610
|
+
.filter(isUnreadableWarning)
|
|
611
|
+
.slice(0, 10)
|
|
612
|
+
.map((warning) => `Not read, so its packages are missing from the SBOM: ${warning}`),
|
|
613
|
+
'To keep it current, regenerate it when dependencies change (the Security Watch GitHub Action can do it on every merge).',
|
|
614
|
+
].join('\n');
|
|
615
|
+
}
|
|
616
|
+
#watchFindings(args, min) {
|
|
617
|
+
let config;
|
|
618
|
+
try {
|
|
619
|
+
config = loadConfig(resolve(this.#config));
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
throw new ToolError(`Could not read the Security Watch configuration ${this.#config}: ${error instanceof Error ? error.message : 'error'}`);
|
|
623
|
+
}
|
|
624
|
+
if (!existsSync(config.database))
|
|
625
|
+
return 'The monitor has no database yet: run security-watch scan or start first.';
|
|
626
|
+
const store = new Store(config.database, { readOnly: true });
|
|
627
|
+
try {
|
|
628
|
+
const ages = maxAges(config.mitigations);
|
|
629
|
+
const order = ['unknown', 'low', 'medium', 'high', 'critical'];
|
|
630
|
+
const limit = typeof args.limit === 'number' && args.limit >= 1 ? Math.min(200, Math.floor(args.limit)) : 50;
|
|
631
|
+
const open = store
|
|
632
|
+
.findings()
|
|
633
|
+
.filter((finding) => finding.active !== false && !finding.withdrawn && finding.category !== 'health')
|
|
634
|
+
.filter((finding) => finding.applicability !== 'not_affected')
|
|
635
|
+
.filter((finding) => typeof args.system !== 'string' || finding.system_id === args.system)
|
|
636
|
+
// A finding without a severity counts as medium, as in the one-off checks.
|
|
637
|
+
.filter((finding) => finding.exploited ||
|
|
638
|
+
order.indexOf(finding.priority === 'unknown' ? 'medium' : finding.priority) >= order.indexOf(min))
|
|
639
|
+
.sort((a, b) => Number(b.exploited) - Number(a.exploited) ||
|
|
640
|
+
order.indexOf(b.priority) - order.indexOf(a.priority) ||
|
|
641
|
+
a.id.localeCompare(b.id))
|
|
642
|
+
.map((finding) => withCurrentMitigations(finding, ages, this.#now()));
|
|
643
|
+
if (!open.length)
|
|
644
|
+
return 'No open findings at or above this priority.';
|
|
645
|
+
return [
|
|
646
|
+
`${open.length} open finding${open.length === 1 ? '' : 's'}${open.length > limit ? `; the first ${limit}` : ''}:`,
|
|
647
|
+
...open
|
|
648
|
+
.slice(0, limit)
|
|
649
|
+
.map((finding) => [
|
|
650
|
+
`- [${finding.priority}] ${finding.title}${finding.exploited ? ' [known exploited]' : ''} (${finding.applicability})`,
|
|
651
|
+
` System: ${finding.location?.system ?? finding.system_id}${finding.location?.owner ? ` (owner: ${finding.location.owner})` : ''}${finding.location?.component ? `; ${finding.location.component}` : ''}`,
|
|
652
|
+
` ${finding.fix ? `Fix: ${finding.fix}. ` : ''}Finding ${finding.id}${finding.urls[0] ? ` ${finding.urls[0]}` : ''}`,
|
|
653
|
+
].join('\n')),
|
|
654
|
+
'',
|
|
655
|
+
'Acknowledge, suppress or review findings with the security-watch CLI; this tool only reads.',
|
|
656
|
+
].join('\n');
|
|
657
|
+
}
|
|
658
|
+
finally {
|
|
659
|
+
store.close();
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
class UnknownTool extends Error {
|
|
664
|
+
}
|
|
665
|
+
function isSbomFile(path) {
|
|
666
|
+
try {
|
|
667
|
+
if (statSync(path).size > 50 * 1024 * 1024)
|
|
668
|
+
return false;
|
|
669
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
670
|
+
return (typeof value === 'object' &&
|
|
671
|
+
value !== null &&
|
|
672
|
+
(value.bomFormat === 'CycloneDX' || typeof value.spdxVersion === 'string'));
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function severity(value) {
|
|
679
|
+
return typeof value === 'string' && SEVERITIES.includes(value)
|
|
680
|
+
? value
|
|
681
|
+
: 'low';
|
|
682
|
+
}
|
|
683
|
+
function clip(text) {
|
|
684
|
+
return text.length > MAX_TEXT
|
|
685
|
+
? `${text.slice(0, MAX_TEXT)}\n\n[Cut at ${MAX_TEXT} characters; narrow it with path or minSeverity.]`
|
|
686
|
+
: text;
|
|
687
|
+
}
|
|
688
|
+
/** Serves MCP over stdio: one JSON-RPC message per line, answered as each finishes. */
|
|
689
|
+
export function serveStdio(options, input = process.stdin, output = process.stdout) {
|
|
690
|
+
const send = (message) => output.write(`${JSON.stringify(message)}\n`);
|
|
691
|
+
const server = new SecurityWatchMcpServer(options, send);
|
|
692
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
693
|
+
lines.on('line', (line) => {
|
|
694
|
+
if (!line.trim())
|
|
695
|
+
return;
|
|
696
|
+
if (line.length > MAX_LINE) {
|
|
697
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Message too large' } });
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
let message;
|
|
701
|
+
try {
|
|
702
|
+
message = JSON.parse(line);
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
for (const item of Array.isArray(message) ? message : [message])
|
|
709
|
+
void server.handle(item);
|
|
710
|
+
});
|
|
711
|
+
return server;
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* `security-watch mcp [project]` and `security-watch-mcp [project]`. The project is the argument,
|
|
715
|
+
* else CLAUDE_PROJECT_DIR, else the working folder, else the first root the client names.
|
|
716
|
+
* SECURITY_WATCH_CONFIG names a monitor configuration for list_watch_findings.
|
|
717
|
+
*/
|
|
718
|
+
export function mcpMain(args) {
|
|
719
|
+
if (args.includes('--help')) {
|
|
720
|
+
process.stdout.write("Usage: security-watch mcp [project]\n security-watch-mcp [project | --client-roots]\n\nAn MCP server (stdio) that checks a project's dependencies for known vulnerabilities.\nSECURITY_WATCH_CONFIG=/path/security-watch.yaml adds list_watch_findings.\n");
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
if (args.includes('--version')) {
|
|
724
|
+
process.stdout.write(`${VERSION}\n`);
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const unknown = args.find((arg) => arg.startsWith('-') && arg !== '--client-roots');
|
|
728
|
+
if (unknown) {
|
|
729
|
+
process.stderr.write(`security-watch mcp: unknown option ${unknown}. Use --help.\n`);
|
|
730
|
+
process.exitCode = 2;
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const argument = args.find((arg) => !arg.startsWith('-'));
|
|
734
|
+
// --client-roots: the caller could not tell which project is open (the plugin launcher, started
|
|
735
|
+
// outside any project); the working folder is not one, so wait for the client to name it.
|
|
736
|
+
const candidate = argument ??
|
|
737
|
+
(args.includes('--client-roots') ? undefined : (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()));
|
|
738
|
+
const root = candidate === undefined ? undefined : resolve(process.cwd(), candidate);
|
|
739
|
+
if (root && !usableRoot(root))
|
|
740
|
+
process.stderr.write(`security-watch mcp: ${root} cannot be the project (a filesystem root, the home folder or not a folder); waiting for the client to name one.\n`);
|
|
741
|
+
const config = process.env.SECURITY_WATCH_CONFIG?.trim();
|
|
742
|
+
serveStdio({ ...(root ? { root } : {}), ...(config ? { config } : {}) });
|
|
743
|
+
}
|
|
744
|
+
function isEntry() {
|
|
745
|
+
if (!process.argv[1])
|
|
746
|
+
return false;
|
|
747
|
+
try {
|
|
748
|
+
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
return false;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
if (isEntry())
|
|
755
|
+
mcpMain(process.argv.slice(2));
|