foster-oss 0.2.1 → 0.3.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/README.md +41 -2
- package/dist/cli.js +64 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/lib/guard.d.ts +35 -0
- package/dist/lib/guard.js +286 -0
- package/dist/mcp.js +15 -0
- package/package.json +6 -2
- package/skills/foster/SKILL.md +6 -0
package/README.md
CHANGED
|
@@ -20,6 +20,7 @@ single import.
|
|
|
20
20
|
npx foster-oss scan # what in my lockfile is orphaned, or vulnerable with no fix?
|
|
21
21
|
npx foster-oss fix # switch to published drop-in patches (edits package.json)
|
|
22
22
|
npx foster-oss check ip@2.0.1
|
|
23
|
+
npx foster-oss guard -- npm install some-package # check before installing (great for AI agents)
|
|
23
24
|
```
|
|
24
25
|
|
|
25
26
|
<p align="center"><img src="brand/demo.svg" alt="foster-oss scan and fix on a small app: two drop-in patches, one orphaned and vulnerable dependency with suggested replacements, and upgrades" width="860"></p>
|
|
@@ -108,6 +109,7 @@ Node 20+. Reads lockfiles from six ecosystems:
|
|
|
108
109
|
| `foster-oss scan [dir]` | Report orphaned and unpatched dependencies. `--recursive` (monorepos), `--json`, `--markdown`, `--sarif <file>`, `--all`, `--fail-on <level>`, `--offline` |
|
|
109
110
|
| `foster-oss fix [dir]` | Point dependencies at published drop-in patches. `--dry-run`, `--force` |
|
|
110
111
|
| `foster-oss check <name[@version]>` | Maintenance status, reach, unfixed advisories, patches and replacements for one package. `--ecosystem pypi\|cargo\|go\|rubygems\|packagist` |
|
|
112
|
+
| `foster-oss guard -- <command>` | Check the packages a shell command would install, before it runs. `--hook claude` for Claude Code, `--strict`, `--json` |
|
|
111
113
|
| `foster-oss mcp` | Start the MCP server for AI agents |
|
|
112
114
|
|
|
113
115
|
What the findings mean:
|
|
@@ -145,14 +147,51 @@ scanning next to your other security alerts.
|
|
|
145
147
|
|
|
146
148
|
### AI agents
|
|
147
149
|
|
|
150
|
+
**Guard: stop agents from installing packages that don't exist or nobody can fix.** Coding agents
|
|
151
|
+
sometimes install hallucinated package names (attackers register them: "slopsquatting"), abandoned
|
|
152
|
+
packages, or versions with known holes. `foster-oss guard` checks every package a shell command
|
|
153
|
+
would install, before it runs:
|
|
154
|
+
|
|
155
|
+
| Situation | Decision |
|
|
156
|
+
|---|---|
|
|
157
|
+
| The name does not exist on the registry | **deny** |
|
|
158
|
+
| A vulnerability that no release fixes | **deny**, with maintained alternatives |
|
|
159
|
+
| Vulnerable version that a newer release fixes, or a drop-in patch exists | **ask** |
|
|
160
|
+
| The package is dead or dormant | **ask**, with maintained alternatives |
|
|
161
|
+
| Everything else | allowed silently |
|
|
162
|
+
|
|
163
|
+
It understands npm, pnpm, yarn, bun, npx/dlx, pip, uv, poetry, pipx, cargo, go, gem, bundle and
|
|
164
|
+
composer commands, including `cd app && npm i -D x` chains.
|
|
165
|
+
|
|
166
|
+
**Claude Code**: add a PreToolUse hook to `.claude/settings.json` (project) or `~/.claude/settings.json` (all projects):
|
|
167
|
+
|
|
168
|
+
```json
|
|
169
|
+
{
|
|
170
|
+
"hooks": {
|
|
171
|
+
"PreToolUse": [
|
|
172
|
+
{
|
|
173
|
+
"matcher": "Bash",
|
|
174
|
+
"hooks": [{ "type": "command", "command": "npx -y foster-oss guard --hook claude", "timeout": 60 }]
|
|
175
|
+
}
|
|
176
|
+
]
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The hook answers with Claude Code's `deny` / `ask` permission decisions and stays silent for commands
|
|
182
|
+
that install nothing. It fails open: if the registry or OSV can't be reached, the normal permission flow
|
|
183
|
+
continues. **Other agents and shells**: `npx foster-oss guard -- <command>` exits 1 when it would deny
|
|
184
|
+
(`--strict` also fails on ask), or call the MCP tool `foster_check_install_command`.
|
|
185
|
+
|
|
148
186
|
**MCP** (Claude Code, Codex, Cursor, …). Listed in the official [MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.foster-oss/foster`, or configure it directly:
|
|
149
187
|
|
|
150
188
|
```json
|
|
151
189
|
{ "mcpServers": { "foster": { "command": "npx", "args": ["-y", "foster-oss", "mcp"] } } }
|
|
152
190
|
```
|
|
153
191
|
|
|
154
|
-
Tools: `
|
|
155
|
-
don't exist, a common sign of a hallucinated
|
|
192
|
+
Tools: `foster_check_install_command` (call it before running an install command), `foster_check_package`
|
|
193
|
+
(call it before adding a dependency; it also catches names that don't exist, a common sign of a hallucinated
|
|
194
|
+
package), `foster_scan_project`, `foster_list_patches`.
|
|
156
195
|
|
|
157
196
|
**Skill**: copy [`skills/foster`](skills/foster/SKILL.md) into your agent's skills folder
|
|
158
197
|
(e.g. `.claude/skills/foster/`).
|
package/dist/cli.js
CHANGED
|
@@ -6,6 +6,7 @@ import { applyFixes, installCommand } from "./lib/fix.js";
|
|
|
6
6
|
import { fosterVersion } from "./lib/http.js";
|
|
7
7
|
import { formatFix, formatMarkdown, formatRecord, formatSarif, formatText } from "./lib/report.js";
|
|
8
8
|
import { describeAlternatives } from "./lib/replacements.js";
|
|
9
|
+
import { guardCommand, parseInstallCommand } from "./lib/guard.js";
|
|
9
10
|
import { scanProject, scanSbom, shouldFail } from "./lib/scan.js";
|
|
10
11
|
import { ECOSYSTEMS } from "./lib/types.js";
|
|
11
12
|
const HELP = `foster-oss ${fosterVersion()}: find dependencies nobody maintains, swap in reviewed patches.
|
|
@@ -16,6 +17,8 @@ Usage:
|
|
|
16
17
|
foster-oss fix [dir] Point dependencies at released drop-in patches (edits package.json)
|
|
17
18
|
foster-oss check <name[@ver]> Look up one package
|
|
18
19
|
foster-oss mcp Start the MCP server (stdio) for AI agents
|
|
20
|
+
foster-oss guard -- <command> Check the packages a shell command would install
|
|
21
|
+
foster-oss guard --hook claude Same, as a Claude Code PreToolUse hook (reads the hook JSON on stdin)
|
|
19
22
|
|
|
20
23
|
Options:
|
|
21
24
|
--json Machine-readable output (scan, check)
|
|
@@ -57,6 +60,9 @@ async function main(argv) {
|
|
|
57
60
|
ecosystem: { type: "string", default: "npm" },
|
|
58
61
|
version: { type: "boolean", short: "v", default: false },
|
|
59
62
|
help: { type: "boolean", short: "h", default: false },
|
|
63
|
+
hook: { type: "string" },
|
|
64
|
+
command: { type: "string" },
|
|
65
|
+
strict: { type: "boolean", default: false },
|
|
60
66
|
},
|
|
61
67
|
});
|
|
62
68
|
const [command, arg] = positionals;
|
|
@@ -122,6 +128,23 @@ ${name}@${version}: no known vulnerabilities.`);
|
|
|
122
128
|
Maintained alternatives: ${describeAlternatives(result.alternatives)}`);
|
|
123
129
|
return 0;
|
|
124
130
|
}
|
|
131
|
+
case "guard": {
|
|
132
|
+
if (values.hook !== undefined) {
|
|
133
|
+
if (values.hook !== "claude")
|
|
134
|
+
throw new UsageError('--hook supports "claude"');
|
|
135
|
+
await runClaudeHook();
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
const line = values.command ?? positionals.slice(1).map((t) => (/s/.test(t) ? JSON.stringify(t) : t)).join(" ");
|
|
139
|
+
if (!line.trim())
|
|
140
|
+
throw new UsageError("guard needs a command, e.g. foster-oss guard -- npm install left-pad");
|
|
141
|
+
const result = await guardCommand(line);
|
|
142
|
+
if (values.json)
|
|
143
|
+
console.log(JSON.stringify(result, null, 2));
|
|
144
|
+
else
|
|
145
|
+
console.log(result.message);
|
|
146
|
+
return result.decision === "deny" || (values.strict && result.decision === "ask") ? 1 : 0;
|
|
147
|
+
}
|
|
125
148
|
case "mcp": {
|
|
126
149
|
const { startMcpServer } = await import("./mcp.js");
|
|
127
150
|
await startMcpServer();
|
|
@@ -133,6 +156,47 @@ Maintained alternatives: ${describeAlternatives(result.alternatives)}`);
|
|
|
133
156
|
}
|
|
134
157
|
class UsageError extends Error {
|
|
135
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Claude Code PreToolUse hook: read the hook JSON from stdin, and for Bash commands that install
|
|
161
|
+
* packages, answer with permissionDecision "deny" or "ask". Silent (no output, exit 0) otherwise.
|
|
162
|
+
* Fails open: any error or a slow network leaves the normal permission flow untouched.
|
|
163
|
+
*/
|
|
164
|
+
async function runClaudeHook() {
|
|
165
|
+
try {
|
|
166
|
+
const raw = await new Promise((resolve, reject) => {
|
|
167
|
+
let data = "";
|
|
168
|
+
process.stdin.setEncoding("utf8");
|
|
169
|
+
process.stdin.on("data", (c) => (data += c));
|
|
170
|
+
process.stdin.on("end", () => resolve(data));
|
|
171
|
+
process.stdin.on("error", reject);
|
|
172
|
+
});
|
|
173
|
+
const input = JSON.parse(raw || "{}");
|
|
174
|
+
if (input.tool_name !== "Bash" || (input.hook_event_name && input.hook_event_name !== "PreToolUse"))
|
|
175
|
+
return;
|
|
176
|
+
const line = input.tool_input?.command ?? "";
|
|
177
|
+
if (parseInstallCommand(line).length === 0)
|
|
178
|
+
return;
|
|
179
|
+
const result = await Promise.race([
|
|
180
|
+
guardCommand(line),
|
|
181
|
+
new Promise((resolve) => setTimeout(() => resolve(null), 25_000).unref()),
|
|
182
|
+
]);
|
|
183
|
+
if (!result || result.decision === "allow")
|
|
184
|
+
return;
|
|
185
|
+
process.stdout.write(JSON.stringify({
|
|
186
|
+
hookSpecificOutput: {
|
|
187
|
+
hookEventName: "PreToolUse",
|
|
188
|
+
permissionDecision: result.decision,
|
|
189
|
+
permissionDecisionReason: result.decision === "deny"
|
|
190
|
+
? `${result.message}
|
|
191
|
+
Do not install it. Tell the user why, and suggest a maintained alternative or a fixed version.`
|
|
192
|
+
: result.message,
|
|
193
|
+
},
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
// fail open
|
|
198
|
+
}
|
|
199
|
+
}
|
|
136
200
|
main(process.argv.slice(2)).then((code) => {
|
|
137
201
|
if (code >= 0)
|
|
138
202
|
process.exitCode = code;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,3 +12,4 @@ export { applyFixes, detectManager, type FixResult, type FixChange } from "./lib
|
|
|
12
12
|
export { checkPackage, parseSpec, type CheckResult } from "./lib/check.js";
|
|
13
13
|
export { formatText, formatMarkdown, formatFix, formatRecord } from "./lib/report.js";
|
|
14
14
|
export { fosterVersion } from "./lib/http.js";
|
|
15
|
+
export { guardCommand, parseInstallCommand, verdictFor, type GuardResult, type RequestedPackage, type Decision } from "./lib/guard.js";
|
package/dist/index.js
CHANGED
|
@@ -12,3 +12,4 @@ export { applyFixes, detectManager } from "./lib/fix.js";
|
|
|
12
12
|
export { checkPackage, parseSpec } from "./lib/check.js";
|
|
13
13
|
export { formatText, formatMarkdown, formatFix, formatRecord } from "./lib/report.js";
|
|
14
14
|
export { fosterVersion } from "./lib/http.js";
|
|
15
|
+
export { guardCommand, parseInstallCommand, verdictFor } from "./lib/guard.js";
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type CheckResult } from "./check.js";
|
|
2
|
+
import type { Ecosystem } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* `foster-oss guard`: inspect a shell command before it runs and stop installs of packages that
|
|
5
|
+
* do not exist (hallucinated or typo'd names, the "slopsquatting" risk), have vulnerabilities no
|
|
6
|
+
* release fixes, or are unmaintained. Built for AI coding agents, usable from any shell.
|
|
7
|
+
*/
|
|
8
|
+
export interface RequestedPackage {
|
|
9
|
+
ecosystem: Ecosystem;
|
|
10
|
+
name: string;
|
|
11
|
+
/** Exact version when the command pins one. */
|
|
12
|
+
version?: string;
|
|
13
|
+
/** The token as written in the command. */
|
|
14
|
+
spec: string;
|
|
15
|
+
}
|
|
16
|
+
export type Decision = "allow" | "ask" | "deny";
|
|
17
|
+
export interface PackageVerdict {
|
|
18
|
+
requested: RequestedPackage;
|
|
19
|
+
decision: Decision;
|
|
20
|
+
reason: string;
|
|
21
|
+
}
|
|
22
|
+
export interface GuardResult {
|
|
23
|
+
decision: Decision;
|
|
24
|
+
verdicts: PackageVerdict[];
|
|
25
|
+
/** One message suitable for showing to an agent or a person. */
|
|
26
|
+
message: string;
|
|
27
|
+
}
|
|
28
|
+
/** Split a shell line into simple commands (on ;, &&, ||, |, newlines) and tokens, honouring quotes. */
|
|
29
|
+
export declare function splitCommands(line: string): string[][];
|
|
30
|
+
/** Package install requests found in a shell command line. Unknown commands yield nothing. */
|
|
31
|
+
export declare function parseInstallCommand(line: string): RequestedPackage[];
|
|
32
|
+
export type Checker = (ecosystem: Ecosystem, name: string, version?: string) => Promise<CheckResult>;
|
|
33
|
+
/** Decide about one package from a live check. */
|
|
34
|
+
export declare function verdictFor(requested: RequestedPackage, check: CheckResult): PackageVerdict;
|
|
35
|
+
export declare function guardCommand(line: string, check?: Checker): Promise<GuardResult>;
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { checkPackage } from "./check.js";
|
|
2
|
+
import { describeAlternatives } from "./replacements.js";
|
|
3
|
+
// ---------------------------------------------------------------- command parsing
|
|
4
|
+
/** Split a shell line into simple commands (on ;, &&, ||, |, newlines) and tokens, honouring quotes. */
|
|
5
|
+
export function splitCommands(line) {
|
|
6
|
+
const commands = [];
|
|
7
|
+
let tokens = [];
|
|
8
|
+
let cur = "";
|
|
9
|
+
let quote = null;
|
|
10
|
+
let hasToken = false;
|
|
11
|
+
const pushToken = () => {
|
|
12
|
+
if (hasToken)
|
|
13
|
+
tokens.push(cur);
|
|
14
|
+
cur = "";
|
|
15
|
+
hasToken = false;
|
|
16
|
+
};
|
|
17
|
+
const pushCommand = () => {
|
|
18
|
+
pushToken();
|
|
19
|
+
if (tokens.length)
|
|
20
|
+
commands.push(tokens);
|
|
21
|
+
tokens = [];
|
|
22
|
+
};
|
|
23
|
+
for (let i = 0; i < line.length; i++) {
|
|
24
|
+
const ch = line[i];
|
|
25
|
+
if (quote) {
|
|
26
|
+
if (ch === quote)
|
|
27
|
+
quote = null;
|
|
28
|
+
else if (ch === "\\" && quote === '"' && i + 1 < line.length)
|
|
29
|
+
cur += line[++i];
|
|
30
|
+
else
|
|
31
|
+
cur += ch;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (ch === '"' || ch === "'") {
|
|
35
|
+
quote = ch;
|
|
36
|
+
hasToken = true;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (ch === "\\" && i + 1 < line.length && line[i + 1] !== "\n") {
|
|
40
|
+
cur += line[++i];
|
|
41
|
+
hasToken = true;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (ch === "\n" || ch === ";" || ch === "|" || (ch === "&" && line[i + 1] === "&")) {
|
|
45
|
+
if (ch === "&" || (ch === "|" && line[i + 1] === "|"))
|
|
46
|
+
i++;
|
|
47
|
+
pushCommand();
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (ch === " " || ch === "\t" || ch === "\r") {
|
|
51
|
+
pushToken();
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
cur += ch;
|
|
55
|
+
hasToken = true;
|
|
56
|
+
}
|
|
57
|
+
pushCommand();
|
|
58
|
+
return commands;
|
|
59
|
+
}
|
|
60
|
+
/** Flags that take a value, per tool, so the value is not mistaken for a package name. */
|
|
61
|
+
const VALUE_FLAGS = {
|
|
62
|
+
npm: ["--registry", "--prefix", "--tag", "--workspace", "-w", "--save-prefix", "--cache", "--userconfig", "--omit", "--include"],
|
|
63
|
+
pnpm: ["--filter", "-F", "--dir", "-C", "--registry", "--workspace"],
|
|
64
|
+
yarn: ["--cwd", "--registry"],
|
|
65
|
+
bun: ["--cwd", "--registry", "--backend"],
|
|
66
|
+
pip: ["-i", "--index-url", "--extra-index-url", "-f", "--find-links", "-c", "--constraint", "-t", "--target", "--prefix", "--root", "--python", "--platform", "--trusted-host", "--src", "--upgrade-strategy", "--only-binary", "--no-binary", "-r", "--requirement", "-e", "--editable"],
|
|
67
|
+
uv: ["--index", "--index-url", "--extra-index-url", "--python", "-p", "--group", "--optional", "--package", "-r", "--requirements", "-e", "--editable", "--directory", "--project", "--find-links", "-f"],
|
|
68
|
+
poetry: ["--group", "-G", "--source", "--extras", "-E", "--python", "--directory", "-C"],
|
|
69
|
+
cargo: ["--features", "-F", "--package", "-p", "--path", "--git", "--branch", "--tag", "--rev", "--registry", "--rename", "--target", "--manifest-path", "--version", "--root"],
|
|
70
|
+
go: ["-C", "-modfile", "-tags"],
|
|
71
|
+
gem: ["-v", "--version", "-s", "--source", "-i", "--install-dir", "--platform"],
|
|
72
|
+
bundle: ["--version", "-v", "--group", "-g", "--source", "-s", "--git", "--github", "--branch", "--ref", "--path"],
|
|
73
|
+
composer: ["--working-dir", "-d"],
|
|
74
|
+
};
|
|
75
|
+
function positional(args, tool) {
|
|
76
|
+
const valueFlags = new Set(VALUE_FLAGS[tool] ?? []);
|
|
77
|
+
const out = [];
|
|
78
|
+
for (let i = 0; i < args.length; i++) {
|
|
79
|
+
const a = args[i];
|
|
80
|
+
if (a === "--") {
|
|
81
|
+
out.push(...args.slice(i + 1));
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
if (a.startsWith("-")) {
|
|
85
|
+
if (!a.includes("=") && valueFlags.has(a))
|
|
86
|
+
i++;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
out.push(a);
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
function flagValue(args, ...names) {
|
|
94
|
+
for (let i = 0; i < args.length; i++) {
|
|
95
|
+
const a = args[i];
|
|
96
|
+
for (const n of names) {
|
|
97
|
+
if (a === n)
|
|
98
|
+
return args[i + 1];
|
|
99
|
+
if (a.startsWith(`${n}=`))
|
|
100
|
+
return a.slice(n.length + 1);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
const LOCAL_OR_URL = /^(\.{0,2}\/|~\/|[a-zA-Z]:\\|file:|link:|workspace:|git(\+|:)|https?:|github:|gitlab:|bitbucket:|ssh:)|\.(tgz|tar\.gz|whl|zip|gem)$/i;
|
|
106
|
+
function npmSpec(spec) {
|
|
107
|
+
if (LOCAL_OR_URL.test(spec))
|
|
108
|
+
return null;
|
|
109
|
+
// "user/repo" without a scope is a GitHub shorthand, not a registry package
|
|
110
|
+
if (!spec.startsWith("@") && spec.includes("/"))
|
|
111
|
+
return null;
|
|
112
|
+
// alias "x@npm:real@1.0.0": check the real package
|
|
113
|
+
const alias = spec.indexOf("@npm:", 1);
|
|
114
|
+
if (alias > 0) {
|
|
115
|
+
const real = spec.slice(alias + "@npm:".length);
|
|
116
|
+
const rat = real.lastIndexOf("@");
|
|
117
|
+
return { ecosystem: "npm", name: rat > 0 ? real.slice(0, rat) : real, version: exact(rat > 0 ? real.slice(rat + 1) : undefined), spec };
|
|
118
|
+
}
|
|
119
|
+
const at = spec.lastIndexOf("@");
|
|
120
|
+
const name = at > 0 ? spec.slice(0, at) : spec;
|
|
121
|
+
let version = at > 0 ? spec.slice(at + 1) : undefined;
|
|
122
|
+
if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/i.test(name))
|
|
123
|
+
return null;
|
|
124
|
+
version = exact(version);
|
|
125
|
+
return { ecosystem: "npm", name, version, spec };
|
|
126
|
+
}
|
|
127
|
+
/** Keep only exact versions; ranges and tags ("^1", "latest") mean "whatever resolves", checked as latest. */
|
|
128
|
+
function exact(v) {
|
|
129
|
+
if (!v)
|
|
130
|
+
return undefined;
|
|
131
|
+
const clean = v.replace(/^[=v]+/, "");
|
|
132
|
+
return /^\d+(\.\d+)*([-.+][0-9A-Za-z.+-]+)?$/.test(clean) ? clean : undefined;
|
|
133
|
+
}
|
|
134
|
+
function pipSpec(spec) {
|
|
135
|
+
if (LOCAL_OR_URL.test(spec) || spec.includes("://") || spec.startsWith("-"))
|
|
136
|
+
return null;
|
|
137
|
+
const m = spec.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*(?:(===?)\s*([^\s;,]+))?/);
|
|
138
|
+
if (!m?.[1])
|
|
139
|
+
return null;
|
|
140
|
+
return { ecosystem: "pypi", name: m[1], version: m[3] ? exact(m[4]) : undefined, spec };
|
|
141
|
+
}
|
|
142
|
+
function cargoSpec(spec) {
|
|
143
|
+
const [name, version] = spec.split("@");
|
|
144
|
+
if (!name || !/^[A-Za-z0-9_-]+$/.test(name))
|
|
145
|
+
return null;
|
|
146
|
+
return { ecosystem: "cargo", name, version: exact(version), spec };
|
|
147
|
+
}
|
|
148
|
+
function goSpec(spec) {
|
|
149
|
+
const at = spec.lastIndexOf("@");
|
|
150
|
+
const path = at > 0 ? spec.slice(0, at) : spec;
|
|
151
|
+
const version = at > 0 ? spec.slice(at + 1) : undefined;
|
|
152
|
+
// module paths have a dot in the first element (github.com/..., golang.org/...); "./..." and "all" are local
|
|
153
|
+
if (!/^[a-z0-9.-]+\.[a-z]{2,}\//i.test(path))
|
|
154
|
+
return null;
|
|
155
|
+
return { ecosystem: "go", name: path, version: version && /^v\d/.test(version) ? version : undefined, spec };
|
|
156
|
+
}
|
|
157
|
+
function gemSpec(spec, version) {
|
|
158
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(spec) || LOCAL_OR_URL.test(spec))
|
|
159
|
+
return null;
|
|
160
|
+
return { ecosystem: "rubygems", name: spec, version: exact(version), spec };
|
|
161
|
+
}
|
|
162
|
+
function composerSpec(spec) {
|
|
163
|
+
const [name, version] = spec.split(/[:=]/);
|
|
164
|
+
if (!name || !/^[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(name))
|
|
165
|
+
return null;
|
|
166
|
+
return { ecosystem: "packagist", name: name.toLowerCase(), version: exact(version), spec };
|
|
167
|
+
}
|
|
168
|
+
/** Package install requests found in a shell command line. Unknown commands yield nothing. */
|
|
169
|
+
export function parseInstallCommand(line) {
|
|
170
|
+
const found = [];
|
|
171
|
+
for (let tokens of splitCommands(line)) {
|
|
172
|
+
// strip env assignments and wrappers
|
|
173
|
+
while (tokens.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0]) || ["sudo", "env", "time", "exec", "command", "nohup"].includes(tokens[0]))) {
|
|
174
|
+
tokens = tokens.slice(1);
|
|
175
|
+
}
|
|
176
|
+
const [cmd0, ...rest] = tokens;
|
|
177
|
+
if (!cmd0)
|
|
178
|
+
continue;
|
|
179
|
+
const cmd = cmd0.replace(/^.*[\\/]/, "").replace(/\.(exe|cmd)$/i, "");
|
|
180
|
+
const sub = rest[0];
|
|
181
|
+
const args = rest.slice(1);
|
|
182
|
+
const add = (r) => r && found.push(r);
|
|
183
|
+
if (cmd === "npm" && sub && ["install", "i", "in", "add", "isntall"].includes(sub))
|
|
184
|
+
positional(args, "npm").forEach((s) => add(npmSpec(s)));
|
|
185
|
+
else if (cmd === "pnpm" && sub && ["add", "install", "i"].includes(sub))
|
|
186
|
+
positional(args, "pnpm").forEach((s) => add(npmSpec(s)));
|
|
187
|
+
else if (cmd === "yarn" && (sub === "add" || (sub === "global" && args[0] === "add")))
|
|
188
|
+
positional(sub === "global" ? args.slice(1) : args, "yarn").forEach((s) => add(npmSpec(s)));
|
|
189
|
+
else if (cmd === "bun" && sub && ["add", "install", "i"].includes(sub))
|
|
190
|
+
positional(args, "bun").forEach((s) => add(npmSpec(s)));
|
|
191
|
+
else if (cmd === "npx" || cmd === "bunx" || (cmd === "pnpm" && sub === "dlx") || (cmd === "yarn" && sub === "dlx")) {
|
|
192
|
+
const runArgs = cmd === "npx" || cmd === "bunx" ? rest : args;
|
|
193
|
+
const pkgFlag = flagValue(runArgs, "-p", "--package");
|
|
194
|
+
const first = pkgFlag ?? positional(runArgs.filter((a) => a !== "-y" && a !== "--yes"), "npm")[0];
|
|
195
|
+
if (first)
|
|
196
|
+
add(npmSpec(first));
|
|
197
|
+
}
|
|
198
|
+
else if (/^pip3?(\.\d+)?$/.test(cmd) && sub === "install")
|
|
199
|
+
positional(args, "pip").forEach((s) => add(pipSpec(s)));
|
|
200
|
+
else if (/^python3?(\.\d+)?$|^py$/.test(cmd) && sub === "-m" && /^pip3?$/.test(args[0] ?? "") && args[1] === "install")
|
|
201
|
+
positional(args.slice(2), "pip").forEach((s) => add(pipSpec(s)));
|
|
202
|
+
else if (cmd === "uv" && sub === "add")
|
|
203
|
+
positional(args, "uv").forEach((s) => add(pipSpec(s)));
|
|
204
|
+
else if (cmd === "uv" && sub === "pip" && args[0] === "install")
|
|
205
|
+
positional(args.slice(1), "uv").forEach((s) => add(pipSpec(s)));
|
|
206
|
+
else if (cmd === "uv" && sub === "tool" && args[0] === "install")
|
|
207
|
+
positional(args.slice(1), "uv").forEach((s) => add(pipSpec(s)));
|
|
208
|
+
else if ((cmd === "poetry" && sub === "add") || (cmd === "pipx" && sub === "install"))
|
|
209
|
+
positional(args, "poetry").forEach((s) => add(pipSpec(s)));
|
|
210
|
+
else if (cmd === "cargo" && (sub === "add" || sub === "install")) {
|
|
211
|
+
const version = flagValue(args, "--version");
|
|
212
|
+
positional(args, "cargo").forEach((s) => {
|
|
213
|
+
const r = cargoSpec(s);
|
|
214
|
+
if (r && !r.version && version)
|
|
215
|
+
r.version = exact(version);
|
|
216
|
+
add(r);
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
else if (cmd === "go" && (sub === "get" || sub === "install"))
|
|
220
|
+
positional(args, "go").forEach((s) => add(goSpec(s)));
|
|
221
|
+
else if (cmd === "gem" && sub === "install") {
|
|
222
|
+
const version = flagValue(args, "-v", "--version");
|
|
223
|
+
positional(args, "gem").forEach((s) => add(gemSpec(s, version)));
|
|
224
|
+
}
|
|
225
|
+
else if (cmd === "bundle" && sub === "add") {
|
|
226
|
+
const version = flagValue(args, "-v", "--version");
|
|
227
|
+
positional(args, "bundle").forEach((s) => add(gemSpec(s, version)));
|
|
228
|
+
}
|
|
229
|
+
else if (cmd === "composer" && (sub === "require" || sub === "req"))
|
|
230
|
+
positional(args, "composer").forEach((s) => add(composerSpec(s)));
|
|
231
|
+
}
|
|
232
|
+
// de-duplicate
|
|
233
|
+
return [...new Map(found.map((r) => [`${r.ecosystem}:${r.name}@${r.version ?? ""}`, r])).values()];
|
|
234
|
+
}
|
|
235
|
+
// ---------------------------------------------------------------- decisions
|
|
236
|
+
const RANK = { allow: 0, ask: 1, deny: 2 };
|
|
237
|
+
/** Decide about one package from a live check. */
|
|
238
|
+
export function verdictFor(requested, check) {
|
|
239
|
+
const label = `${requested.name}${requested.version ? `@${requested.version}` : ""} (${requested.ecosystem})`;
|
|
240
|
+
if (check.notFound) {
|
|
241
|
+
return { requested, decision: "deny", reason: `${label} does not exist on the registry. It may be a misspelled or hallucinated name; attackers register such names ("slopsquatting"). Check the exact package name first.` };
|
|
242
|
+
}
|
|
243
|
+
const alt = check.alternatives ? ` Maintained alternatives: ${describeAlternatives(check.alternatives)}.` : "";
|
|
244
|
+
const finding = check.findings[0];
|
|
245
|
+
if (finding?.kind === "patch-available" && finding.patch) {
|
|
246
|
+
return { requested, decision: "ask", reason: `${label} has ${finding.advisories.map((a) => a.id).join(", ")} with no upstream fix. A drop-in patch exists: ${finding.patch.replacement.name}@${finding.patch.replacement.version} (run \`npx foster-oss fix\` after installing).${alt}` };
|
|
247
|
+
}
|
|
248
|
+
if (finding?.kind === "orphaned-vulnerable" || finding?.kind === "unpatched-vulnerable") {
|
|
249
|
+
const status = check.record?.status ?? "unknown";
|
|
250
|
+
return { requested, decision: "deny", reason: `${label} has security advisories that no release fixes (${finding.advisories.map((a) => `${a.id} ${a.severity}`).join(", ")}); maintenance: ${status}.${alt}` };
|
|
251
|
+
}
|
|
252
|
+
if (finding?.kind === "upgrade-available") {
|
|
253
|
+
return { requested, decision: "ask", reason: `${label} is vulnerable (${finding.advisories.map((a) => a.id).join(", ")}); ${finding.fixedIn ? `version ${finding.fixedIn} fixes it` : "a newer release fixes it"}. Install a fixed version instead.` };
|
|
254
|
+
}
|
|
255
|
+
const status = check.record?.status;
|
|
256
|
+
if (status === "dead" || status === "dormant") {
|
|
257
|
+
return { requested, decision: "ask", reason: `${label} looks ${status} (${check.record.reasons.join("; ")}). Nobody may fix future security problems.${alt || " Prefer a maintained package if one exists."}` };
|
|
258
|
+
}
|
|
259
|
+
return { requested, decision: "allow", reason: `${label}: ok` };
|
|
260
|
+
}
|
|
261
|
+
export async function guardCommand(line, check = checkPackage) {
|
|
262
|
+
const requested = parseInstallCommand(line);
|
|
263
|
+
const verdicts = [];
|
|
264
|
+
for (const r of requested) {
|
|
265
|
+
try {
|
|
266
|
+
// With no pinned version, check the version that would be installed: the latest release.
|
|
267
|
+
let result = await check(r.ecosystem, r.name, r.version);
|
|
268
|
+
if (!r.version && result.record?.latestVersion && !result.notFound) {
|
|
269
|
+
result = await check(r.ecosystem, r.name, result.record.latestVersion);
|
|
270
|
+
}
|
|
271
|
+
verdicts.push(verdictFor(r, result));
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
// Fail open: a network problem must not block development, but say so.
|
|
275
|
+
verdicts.push({ requested: r, decision: "allow", reason: `${r.name} (${r.ecosystem}): could not be checked (${err.message})` });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const decision = verdicts.reduce((d, v) => (RANK[v.decision] > RANK[d] ? v.decision : d), "allow");
|
|
279
|
+
const flagged = verdicts.filter((v) => v.decision !== "allow");
|
|
280
|
+
const message = flagged.length === 0
|
|
281
|
+
? requested.length
|
|
282
|
+
? `Foster guard: ${requested.length} package(s) checked, nothing to flag.`
|
|
283
|
+
: "Foster guard: no package installs in this command."
|
|
284
|
+
: `Foster guard ${decision === "deny" ? "blocked" : "flagged"} this install:\n${flagged.map((v) => `- ${v.reason}`).join("\n")}`;
|
|
285
|
+
return { decision, verdicts, message };
|
|
286
|
+
}
|
package/dist/mcp.js
CHANGED
|
@@ -6,6 +6,7 @@ import { loadRegistry } from "./lib/data.js";
|
|
|
6
6
|
import { fosterVersion } from "./lib/http.js";
|
|
7
7
|
import { formatMarkdown, formatRecord } from "./lib/report.js";
|
|
8
8
|
import { scanProject } from "./lib/scan.js";
|
|
9
|
+
import { guardCommand } from "./lib/guard.js";
|
|
9
10
|
import { describeAlternatives } from "./lib/replacements.js";
|
|
10
11
|
function text(s) {
|
|
11
12
|
return { content: [{ type: "text", text: s }] };
|
|
@@ -52,6 +53,20 @@ export function createMcpServer() {
|
|
|
52
53
|
const result = await scanProject(path, { recursive });
|
|
53
54
|
return text(formatMarkdown(result));
|
|
54
55
|
});
|
|
56
|
+
server.registerTool("foster_check_install_command", {
|
|
57
|
+
title: "Check an install command before running it",
|
|
58
|
+
description: "Before running a shell command that installs packages (npm/pnpm/yarn/bun, npx, pip/uv/poetry, cargo, go get, gem, composer), " +
|
|
59
|
+
"check every package it would install. Returns deny for names that do not exist (hallucinated or typo'd) and for " +
|
|
60
|
+
"vulnerabilities no release fixes, ask for unmaintained packages or fixable vulnerable versions, allow otherwise.",
|
|
61
|
+
inputSchema: {
|
|
62
|
+
command: z.string().describe("The exact shell command you are about to run, e.g. 'npm install left-pad'"),
|
|
63
|
+
},
|
|
64
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
65
|
+
}, async ({ command }) => {
|
|
66
|
+
const r = await guardCommand(command);
|
|
67
|
+
return text(`Decision: ${r.decision.toUpperCase()}
|
|
68
|
+
${r.message}`);
|
|
69
|
+
});
|
|
55
70
|
server.registerTool("foster_list_patches", {
|
|
56
71
|
title: "List known drop-in patches",
|
|
57
72
|
description: "List known drop-in security patches for abandoned packages (Foster and other providers), with the versions they replace and the advisories they fix.",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foster-oss",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"mcpName": "io.github.foster-oss/foster",
|
|
5
5
|
"description": "Find dependencies nobody maintains anymore (npm, PyPI, Cargo, Go, RubyGems, Packagist), and switch to published drop-in security patches without changing your imports.",
|
|
6
6
|
"keywords": [
|
|
@@ -19,7 +19,11 @@
|
|
|
19
19
|
"php",
|
|
20
20
|
"python",
|
|
21
21
|
"sarif",
|
|
22
|
-
"code-scanning"
|
|
22
|
+
"code-scanning",
|
|
23
|
+
"guard",
|
|
24
|
+
"hallucination",
|
|
25
|
+
"slopsquatting",
|
|
26
|
+
"claude-code"
|
|
23
27
|
],
|
|
24
28
|
"license": "Apache-2.0",
|
|
25
29
|
"type": "module",
|
package/skills/foster/SKILL.md
CHANGED
|
@@ -49,6 +49,12 @@ If the MCP server is configured (`npx -y foster-oss mcp`), prefer its tools:
|
|
|
49
49
|
| `ORPHANED` | Widely used, unmaintained, no known vulnerability | Informational. Avoid for *new* code; a `consider:` line names maintained replacements when known |
|
|
50
50
|
| "not found" | The name does not exist on the registry | Likely a typo or hallucinated package: do **not** install it |
|
|
51
51
|
|
|
52
|
+
## Before running an install command
|
|
53
|
+
|
|
54
|
+
Run `npx -y foster-oss guard -- <the exact command>` (or the MCP tool `foster_check_install_command`).
|
|
55
|
+
If it says **deny**, do not run the command: tell the user why and offer the suggested alternative or a
|
|
56
|
+
fixed version. If it says **ask**, show the user the reason and let them decide.
|
|
57
|
+
|
|
52
58
|
## Rules
|
|
53
59
|
|
|
54
60
|
- Never run `foster-oss fix` without telling the user what will change; run `--dry-run` first.
|