foster-oss 0.0.0-stage → 0.2.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/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ import { appendFileSync, writeFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { checkPackage, parseSpec } from "./lib/check.js";
5
+ import { applyFixes, installCommand } from "./lib/fix.js";
6
+ import { fosterVersion } from "./lib/http.js";
7
+ import { formatFix, formatMarkdown, formatRecord, formatSarif, formatText } from "./lib/report.js";
8
+ import { describeAlternatives } from "./lib/replacements.js";
9
+ import { scanProject, scanSbom, shouldFail } from "./lib/scan.js";
10
+ import { ECOSYSTEMS } from "./lib/types.js";
11
+ const HELP = `foster-oss ${fosterVersion()}: find dependencies nobody maintains, swap in reviewed patches.
12
+
13
+ Usage:
14
+ foster-oss scan [dir] Check a project's lockfiles
15
+ foster-oss scan --sbom <file> Check a CycloneDX or SPDX JSON SBOM instead
16
+ foster-oss fix [dir] Point dependencies at released drop-in patches (edits package.json)
17
+ foster-oss check <name[@ver]> Look up one package
18
+ foster-oss mcp Start the MCP server (stdio) for AI agents
19
+
20
+ Options:
21
+ --json Machine-readable output (scan, check)
22
+ --markdown Markdown report (scan)
23
+ --all List every unmaintained dependency, not only the vulnerable ones (scan)
24
+ -r, --recursive Also scan lockfiles in subfolders (monorepos)
25
+ --summary-file <path> Also append the markdown report to this file (e.g. $GITHUB_STEP_SUMMARY)
26
+ --sarif <path> Also write a SARIF 2.1.0 report (GitHub code scanning, other dashboards)
27
+ --fail-on <level> Exit 1 when findings reach a level:
28
+ none | patch-available | orphaned-vulnerable | unpatched | any (default: none)
29
+ --offline Use only data bundled with this release (no network)
30
+ --include-staged Also use patches that are reviewed but not yet released
31
+ --dry-run Show what fix would change without writing
32
+ --force Replace existing overrides for the same package (fix)
33
+ --ecosystem <name> Ecosystem for check: npm, pypi, cargo, go, rubygems, packagist (default: npm)
34
+ -v, --version Print version
35
+ -h, --help Show this help
36
+
37
+ Data: ecosyste.ms (maintenance, reach), OSV.dev (vulnerabilities), patch registry (Foster and other providers such as Keep LTS).
38
+ Docs: https://github.com/foster-oss/foster`;
39
+ const FAIL_LEVELS = ["none", "patch-available", "orphaned-vulnerable", "unpatched", "any"];
40
+ async function main(argv) {
41
+ const { values, positionals } = parseArgs({
42
+ args: argv,
43
+ allowPositionals: true,
44
+ options: {
45
+ json: { type: "boolean", default: false },
46
+ all: { type: "boolean", default: false },
47
+ markdown: { type: "boolean", default: false },
48
+ "summary-file": { type: "string" },
49
+ sarif: { type: "string" },
50
+ sbom: { type: "string" },
51
+ recursive: { type: "boolean", short: "r", default: false },
52
+ "fail-on": { type: "string", default: "none" },
53
+ offline: { type: "boolean", default: false },
54
+ "include-staged": { type: "boolean", default: false },
55
+ "dry-run": { type: "boolean", default: false },
56
+ force: { type: "boolean", default: false },
57
+ ecosystem: { type: "string", default: "npm" },
58
+ version: { type: "boolean", short: "v", default: false },
59
+ help: { type: "boolean", short: "h", default: false },
60
+ },
61
+ });
62
+ const [command, arg] = positionals;
63
+ if (values.version) {
64
+ console.log(fosterVersion());
65
+ return 0;
66
+ }
67
+ if (values.help || !command) {
68
+ console.log(HELP);
69
+ return command || values.help ? 0 : 1;
70
+ }
71
+ switch (command) {
72
+ case "scan": {
73
+ const failOn = values["fail-on"];
74
+ if (!FAIL_LEVELS.includes(failOn))
75
+ throw new UsageError(`--fail-on must be one of ${FAIL_LEVELS.join(", ")}`);
76
+ const scanOpts = { offline: values.offline, includeStaged: values["include-staged"], recursive: values.recursive };
77
+ const result = values.sbom ? await scanSbom(values.sbom, scanOpts) : await scanProject(arg ?? ".", scanOpts);
78
+ if (values.json)
79
+ console.log(JSON.stringify(result, null, 2));
80
+ else if (values.markdown)
81
+ console.log(formatMarkdown(result));
82
+ else
83
+ console.log(formatText(result, process.stdout.isTTY ?? false, values.all));
84
+ if (values["summary-file"])
85
+ appendFileSync(values["summary-file"], formatMarkdown(result) + "\n");
86
+ if (values.sarif)
87
+ writeFileSync(values.sarif, formatSarif(result, fosterVersion(), process.cwd(), values.all));
88
+ return shouldFail(result.findings, failOn) ? 1 : 0;
89
+ }
90
+ case "fix": {
91
+ const dir = arg ?? ".";
92
+ const scan = await scanProject(dir, { offline: values.offline, includeStaged: values["include-staged"] });
93
+ const result = applyFixes(dir, scan.findings, { dryRun: values["dry-run"], force: values.force });
94
+ console.log(formatFix(result, installCommand(result.manager)));
95
+ return 0;
96
+ }
97
+ case "check": {
98
+ if (!arg)
99
+ throw new UsageError("check needs a package name, e.g. foster-oss check ip@2.0.1");
100
+ const ecosystem = values.ecosystem;
101
+ if (!ECOSYSTEMS.includes(ecosystem))
102
+ throw new UsageError(`--ecosystem must be one of ${ECOSYSTEMS.join(", ")}`);
103
+ const { name, version } = parseSpec(arg);
104
+ const result = await checkPackage(ecosystem, name, version, { includeStaged: values["include-staged"] });
105
+ if (values.json) {
106
+ console.log(JSON.stringify(result, null, 2));
107
+ return 0;
108
+ }
109
+ if (result.notFound) {
110
+ console.log(`${name} was not found on ${ecosystem}.`);
111
+ return 1;
112
+ }
113
+ if (result.record)
114
+ console.log(formatRecord(result.record));
115
+ for (const f of result.findings)
116
+ console.log(`\n${f.message}`);
117
+ if (version && result.findings.length === 0)
118
+ console.log(`
119
+ ${name}@${version}: no known vulnerabilities.`);
120
+ if (result.alternatives && result.record && result.record.status !== "active")
121
+ console.log(`
122
+ Maintained alternatives: ${describeAlternatives(result.alternatives)}`);
123
+ return 0;
124
+ }
125
+ case "mcp": {
126
+ const { startMcpServer } = await import("./mcp.js");
127
+ await startMcpServer();
128
+ return -1; // keep running
129
+ }
130
+ default:
131
+ throw new UsageError(`unknown command "${command}". Run foster-oss --help.`);
132
+ }
133
+ }
134
+ class UsageError extends Error {
135
+ }
136
+ main(process.argv.slice(2)).then((code) => {
137
+ if (code >= 0)
138
+ process.exitCode = code;
139
+ }, (err) => {
140
+ if (err instanceof UsageError || err.code?.startsWith("ERR_PARSE_ARGS")) {
141
+ console.error(`foster-oss: ${err.message}`);
142
+ process.exitCode = 2;
143
+ }
144
+ else {
145
+ console.error(`foster-oss: ${err.stack ?? err}`);
146
+ process.exitCode = 3;
147
+ }
148
+ });
@@ -0,0 +1,14 @@
1
+ export * from "./lib/types.js";
2
+ export { classify, toOrphanRecord, unpatchedAdvisories, maxSeverity } from "./lib/classify.js";
3
+ export { getPackage, listCriticalPage, type RawPackage } from "./lib/ecosystems.js";
4
+ export { queryBatch, getVuln, describeForDependency } from "./lib/osv.js";
5
+ export { detectLockfiles, readDependencies, parsePackageLock, parsePnpmLock, parseYarnLock, parseRequirements, parseUvLock, } from "./lib/lockfile.js";
6
+ export { loadRegistry, loadOrphanIndex, findPatch, indexByName, type PatchRegistry, type OrphanIndexFile } from "./lib/data.js";
7
+ export { scanProject, scanSbom, analyzeDependencies, shouldFail, type ScanOptions, type FailOn } from "./lib/scan.js";
8
+ export { readSbom, parsePurl } from "./lib/sbom.js";
9
+ export { alternativesFor } from "./lib/replacements.js";
10
+ export { formatSarif } from "./lib/report.js";
11
+ export { applyFixes, detectManager, type FixResult, type FixChange } from "./lib/fix.js";
12
+ export { checkPackage, parseSpec, type CheckResult } from "./lib/check.js";
13
+ export { formatText, formatMarkdown, formatFix, formatRecord } from "./lib/report.js";
14
+ export { fosterVersion } from "./lib/http.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export * from "./lib/types.js";
2
+ export { classify, toOrphanRecord, unpatchedAdvisories, maxSeverity } from "./lib/classify.js";
3
+ export { getPackage, listCriticalPage } from "./lib/ecosystems.js";
4
+ export { queryBatch, getVuln, describeForDependency } from "./lib/osv.js";
5
+ export { detectLockfiles, readDependencies, parsePackageLock, parsePnpmLock, parseYarnLock, parseRequirements, parseUvLock, } from "./lib/lockfile.js";
6
+ export { loadRegistry, loadOrphanIndex, findPatch, indexByName } from "./lib/data.js";
7
+ export { scanProject, scanSbom, analyzeDependencies, shouldFail } from "./lib/scan.js";
8
+ export { readSbom, parsePurl } from "./lib/sbom.js";
9
+ export { alternativesFor } from "./lib/replacements.js";
10
+ export { formatSarif } from "./lib/report.js";
11
+ export { applyFixes, detectManager } from "./lib/fix.js";
12
+ export { checkPackage, parseSpec } from "./lib/check.js";
13
+ export { formatText, formatMarkdown, formatFix, formatRecord } from "./lib/report.js";
14
+ export { fosterVersion } from "./lib/http.js";
@@ -0,0 +1,23 @@
1
+ import { type AlternativeSet } from "./replacements.js";
2
+ import type { Ecosystem, Finding, OrphanRecord, PatchEntry } from "./types.js";
3
+ export interface CheckResult {
4
+ ecosystem: Ecosystem;
5
+ name: string;
6
+ version?: string;
7
+ record: OrphanRecord | null;
8
+ /** Findings for the given version (only when a version was supplied). */
9
+ findings: Finding[];
10
+ patch?: PatchEntry;
11
+ notFound: boolean;
12
+ /** Maintained replacements (npm only). */
13
+ alternatives?: AlternativeSet;
14
+ }
15
+ /** Parse "name", "name@1.2.3" or "@scope/name@1.2.3". */
16
+ export declare function parseSpec(spec: string): {
17
+ name: string;
18
+ version?: string;
19
+ };
20
+ /** Live check of one package: maintenance status, unpatched advisories and Foster patches. */
21
+ export declare function checkPackage(ecosystem: Ecosystem, name: string, version?: string, opts?: {
22
+ includeStaged?: boolean;
23
+ }): Promise<CheckResult>;
@@ -0,0 +1,36 @@
1
+ import { alternativesFor } from "./replacements.js";
2
+ import { toOrphanRecord } from "./classify.js";
3
+ import { findPatch, indexKey, loadRegistry } from "./data.js";
4
+ import { getPackage } from "./ecosystems.js";
5
+ import { HttpError } from "./http.js";
6
+ import { analyzeDependencies } from "./scan.js";
7
+ /** Parse "name", "name@1.2.3" or "@scope/name@1.2.3". */
8
+ export function parseSpec(spec) {
9
+ const at = spec.lastIndexOf("@");
10
+ if (at > 0)
11
+ return { name: spec.slice(0, at), version: spec.slice(at + 1) || undefined };
12
+ return { name: spec };
13
+ }
14
+ /** Live check of one package: maintenance status, unpatched advisories and Foster patches. */
15
+ export async function checkPackage(ecosystem, name, version, opts = {}) {
16
+ let record = null;
17
+ let notFound = false;
18
+ try {
19
+ record = toOrphanRecord(await getPackage(ecosystem, name), ecosystem);
20
+ }
21
+ catch (err) {
22
+ if (err instanceof HttpError && err.status === 404)
23
+ notFound = true;
24
+ else
25
+ throw err;
26
+ }
27
+ let findings = [];
28
+ let patch;
29
+ if (version) {
30
+ const dep = { ecosystem, name, version, direct: true, source: "cli" };
31
+ const records = new Map(record ? [[indexKey(ecosystem, name), record]] : []);
32
+ findings = await analyzeDependencies([dep], { includeStaged: opts.includeStaged, deep: false, records });
33
+ patch = findPatch(await loadRegistry(), dep, opts.includeStaged);
34
+ }
35
+ return { ecosystem, name, version, record, findings, patch, notFound, alternatives: alternativesFor(ecosystem, name) };
36
+ }
@@ -0,0 +1,27 @@
1
+ import type { RawPackage } from "./ecosystems.js";
2
+ import type { AdvisorySummary, Ecosystem, MaintenanceStatus, OrphanRecord, Severity } from "./types.js";
3
+ export interface Classification {
4
+ status: MaintenanceStatus;
5
+ reasons: string[];
6
+ }
7
+ /**
8
+ * Classify how well a package is maintained, using only public metadata.
9
+ *
10
+ * This mirrors the buckets used by Andrew Nesbitt's 2026 analysis of the ecosyste.ms critical set
11
+ * (Active / Dormant / Dead / Unknown). "Write-access response" is approximated by closes and merges,
12
+ * because ecosyste.ms does not expose who responded. See METHODOLOGY.md.
13
+ */
14
+ export declare function classify(pkg: RawPackage, now?: Date): Classification;
15
+ export declare function normalizeSeverity(s: string | null | undefined): Severity;
16
+ export declare const SEVERITY_WEIGHT: Record<Severity, number>;
17
+ export declare function maxSeverity(list: {
18
+ severity: Severity;
19
+ }[]): Severity;
20
+ /**
21
+ * Advisories against this package that no release fixes: no patched version is published
22
+ * AND the latest release is still inside the vulnerable range.
23
+ * Withdrawn advisories and malware/hijack reports are skipped: those need "avoid this version", not a patch.
24
+ */
25
+ export declare function unpatchedAdvisories(pkg: RawPackage, ecosystem: Ecosystem): AdvisorySummary[];
26
+ /** Build an Orphan Index row from a raw ecosyste.ms package record. */
27
+ export declare function toOrphanRecord(pkg: RawPackage, ecosystem: Ecosystem, now?: Date): OrphanRecord;
@@ -0,0 +1,183 @@
1
+ import { rangeIncludes } from "./versions.js";
2
+ const DAY = 24 * 60 * 60 * 1000;
3
+ function ageDays(iso, now) {
4
+ if (!iso)
5
+ return null;
6
+ const t = Date.parse(iso);
7
+ if (Number.isNaN(t))
8
+ return null;
9
+ return Math.floor((now.getTime() - t) / DAY);
10
+ }
11
+ /**
12
+ * Classify how well a package is maintained, using only public metadata.
13
+ *
14
+ * This mirrors the buckets used by Andrew Nesbitt's 2026 analysis of the ecosyste.ms critical set
15
+ * (Active / Dormant / Dead / Unknown). "Write-access response" is approximated by closes and merges,
16
+ * because ecosyste.ms does not expose who responded. See METHODOLOGY.md.
17
+ */
18
+ export function classify(pkg, now = new Date()) {
19
+ const repo = pkg.repo_metadata ?? null;
20
+ const issues = pkg.issue_metadata ?? null;
21
+ const releaseAge = ageDays(pkg.latest_release_published_at, now);
22
+ const pushAge = ageDays(repo?.pushed_at, now);
23
+ if (pkg.status && ["removed", "deprecated"].includes(pkg.status)) {
24
+ return { status: "dead", reasons: [`registry marks the package as ${pkg.status}`] };
25
+ }
26
+ if (!repo) {
27
+ if (releaseAge !== null && releaseAge > 730) {
28
+ return { status: "dormant", reasons: ["no linked source repository", `no release for ${years(releaseAge)}`] };
29
+ }
30
+ return { status: "unknown", reasons: ["no linked source repository"] };
31
+ }
32
+ if (repo.archived) {
33
+ return { status: "dead", reasons: ["source repository is archived"] };
34
+ }
35
+ // No push date and no release date: we cannot tell, so do not guess dead or dormant.
36
+ if (!repo.pushed_at && !pkg.latest_release_published_at) {
37
+ return { status: "unknown", reasons: ["no activity dates available"] };
38
+ }
39
+ const reasons = [];
40
+ const pushedRecently = pushAge !== null && pushAge <= 365;
41
+ const releasedRecently = releaseAge !== null && releaseAge <= 365;
42
+ if (issues) {
43
+ const opened = (issues.past_year_issues_count ?? 0) + (issues.past_year_pull_requests_count ?? 0);
44
+ const closed = (issues.past_year_issues_closed_count ?? 0) + (issues.past_year_pull_requests_closed_count ?? 0);
45
+ const merged = issues.past_year_merged_pull_requests_count ?? 0;
46
+ if (opened > 0 && closed === 0 && merged === 0 && !pushedRecently && !releasedRecently) {
47
+ reasons.push(`${opened} issue(s)/PR(s) opened in the past year, none closed or merged`);
48
+ if (pushAge !== null)
49
+ reasons.push(`last push ${years(pushAge)} ago`);
50
+ return { status: "dead", reasons };
51
+ }
52
+ }
53
+ if (!pushedRecently && !releasedRecently) {
54
+ if (releaseAge !== null)
55
+ reasons.push(`no release for ${years(releaseAge)}`);
56
+ if (pushAge !== null)
57
+ reasons.push(`no push for ${years(pushAge)}`);
58
+ if (reasons.length === 0)
59
+ reasons.push("no recent release or push");
60
+ return { status: "dormant", reasons };
61
+ }
62
+ if (!issues && releaseAge === null && pushAge === null) {
63
+ return { status: "unknown", reasons: ["not enough activity data"] };
64
+ }
65
+ return { status: "active", reasons: [] };
66
+ }
67
+ function years(days) {
68
+ if (days < 60)
69
+ return `${days} days`;
70
+ if (days < 730)
71
+ return `${Math.round(days / 30)} months`;
72
+ return `${(days / 365).toFixed(1)} years`;
73
+ }
74
+ const SEVERITIES = ["CRITICAL", "HIGH", "MODERATE", "LOW"];
75
+ export function normalizeSeverity(s) {
76
+ const up = (s ?? "").toUpperCase();
77
+ if (up === "MEDIUM")
78
+ return "MODERATE";
79
+ return SEVERITIES.includes(up) ? up : "UNKNOWN";
80
+ }
81
+ export const SEVERITY_WEIGHT = {
82
+ CRITICAL: 10,
83
+ HIGH: 7,
84
+ MODERATE: 4,
85
+ LOW: 1,
86
+ UNKNOWN: 2,
87
+ };
88
+ export function maxSeverity(list) {
89
+ let best = "UNKNOWN";
90
+ let bestWeight = -1;
91
+ for (const a of list) {
92
+ const order = SEVERITIES.indexOf(a.severity);
93
+ const w = order === -1 ? -0.5 : SEVERITIES.length - order;
94
+ if (w > bestWeight) {
95
+ bestWeight = w;
96
+ best = a.severity;
97
+ }
98
+ }
99
+ return best;
100
+ }
101
+ /** How each ecosystem is spelled in GitHub/ecosyste.ms advisory records. */
102
+ const ADVISORY_ECOSYSTEM = {
103
+ npm: ["npm"],
104
+ pypi: ["pypi", "pip"],
105
+ cargo: ["cargo", "crates.io", "rust"],
106
+ go: ["go", "golang"],
107
+ rubygems: ["rubygems", "gem"],
108
+ packagist: ["packagist", "composer"],
109
+ };
110
+ /** Same pattern as MALWARE_TITLE in osv.ts; duplicated to keep this module free of network code. */
111
+ const MALWARE_TITLE = /malicious|malware|compromised|hijack|embedded .*(code|payload)|protestware|sabotage/i;
112
+ /**
113
+ * Advisories against this package that no release fixes: no patched version is published
114
+ * AND the latest release is still inside the vulnerable range.
115
+ * Withdrawn advisories and malware/hijack reports are skipped: those need "avoid this version", not a patch.
116
+ */
117
+ export function unpatchedAdvisories(pkg, ecosystem) {
118
+ const out = [];
119
+ const seen = new Set();
120
+ const latest = pkg.latest_release_number ?? null;
121
+ for (const adv of pkg.advisories ?? []) {
122
+ if (adv.withdrawn_at)
123
+ continue;
124
+ if ((adv.classification ?? "").toUpperCase() === "MALWARE")
125
+ continue;
126
+ if (MALWARE_TITLE.test(adv.title ?? ""))
127
+ continue;
128
+ for (const p of adv.packages ?? []) {
129
+ if (p.package_name !== pkg.name)
130
+ continue;
131
+ if (p.ecosystem && !ADVISORY_ECOSYSTEM[ecosystem].includes(p.ecosystem.toLowerCase()))
132
+ continue;
133
+ for (const v of p.versions ?? []) {
134
+ if (v.first_patched_version)
135
+ continue;
136
+ // If the newest release is outside the range, upgrading fixes it: not an orphan problem.
137
+ if (latest && !rangeIncludes(v.vulnerable_version_range ?? undefined, latest))
138
+ continue;
139
+ const id = adv.identifiers?.find((x) => x.startsWith("GHSA-")) ?? adv.url?.split("/").pop() ?? adv.uuid ?? "unknown";
140
+ const key = `${id}|${v.vulnerable_version_range ?? ""}`;
141
+ if (seen.has(key))
142
+ continue;
143
+ seen.add(key);
144
+ out.push({
145
+ id,
146
+ url: adv.url ?? `https://github.com/advisories/${id}`,
147
+ severity: normalizeSeverity(adv.severity),
148
+ title: adv.title ?? id,
149
+ range: v.vulnerable_version_range ?? undefined,
150
+ });
151
+ }
152
+ }
153
+ }
154
+ return out;
155
+ }
156
+ const STATUS_WEIGHT = { dead: 3, dormant: 2, unknown: 1, active: 0 };
157
+ /** Build an Orphan Index row from a raw ecosyste.ms package record. */
158
+ export function toOrphanRecord(pkg, ecosystem, now = new Date()) {
159
+ const { status, reasons } = classify(pkg, now);
160
+ const advisories = unpatchedAdvisories(pkg, ecosystem);
161
+ const dependentRepos = pkg.dependent_repos_count ?? null;
162
+ const dependentPackages = pkg.dependent_packages_count ?? null;
163
+ const reach = Math.log10(1 + (dependentRepos ?? 0) + 10 * (dependentPackages ?? 0) + (pkg.downloads ?? 0) / 1000);
164
+ const advWeight = advisories.length ? SEVERITY_WEIGHT[maxSeverity(advisories)] : 1;
165
+ const priority = Math.round(reach * STATUS_WEIGHT[status] * advWeight * 10) / 10;
166
+ return {
167
+ ecosystem,
168
+ name: pkg.name,
169
+ status,
170
+ reasons,
171
+ downloadsLastMonth: pkg.downloads_period === "last-month" ? (pkg.downloads ?? null) : null,
172
+ dependentRepos,
173
+ dependentPackages,
174
+ latestVersion: pkg.latest_release_number ?? null,
175
+ latestReleaseAt: pkg.latest_release_published_at ?? null,
176
+ repoUrl: pkg.repo_metadata?.html_url ?? pkg.repository_url ?? null,
177
+ archived: Boolean(pkg.repo_metadata?.archived),
178
+ lastPushAt: pkg.repo_metadata?.pushed_at ?? null,
179
+ publishers: Array.isArray(pkg.maintainers) ? pkg.maintainers.length : null,
180
+ unpatchedAdvisories: advisories,
181
+ priority,
182
+ };
183
+ }
@@ -0,0 +1,26 @@
1
+ import type { Dependency, Ecosystem, OrphanRecord, PatchEntry } from "./types.js";
2
+ /** Where the public copies live once the repository is published. Overridable for forks and tests. */
3
+ export declare const REMOTE_REGISTRY_URL: string;
4
+ export declare const REMOTE_INDEX_URL: string;
5
+ export interface PatchRegistry {
6
+ version: 1;
7
+ patches: PatchEntry[];
8
+ }
9
+ export interface OrphanIndexFile {
10
+ version: 1;
11
+ generatedAt: string;
12
+ source: string;
13
+ records: OrphanRecord[];
14
+ }
15
+ export interface LoadOptions {
16
+ /** Skip the network and use only the copy bundled with this release. */
17
+ offline?: boolean;
18
+ /** Explicit local file to load instead of the bundled/remote copy. */
19
+ file?: string;
20
+ }
21
+ export declare function loadRegistry(opts?: LoadOptions, warnings?: string[]): Promise<PatchRegistry>;
22
+ export declare function loadOrphanIndex(opts?: LoadOptions, warnings?: string[]): Promise<OrphanIndexFile>;
23
+ export declare function indexKey(ecosystem: Ecosystem, name: string): string;
24
+ export declare function indexByName(file: OrphanIndexFile): Map<string, OrphanRecord>;
25
+ /** Find the patch that applies to this exact installed version. */
26
+ export declare function findPatch(registry: PatchRegistry, dep: Dependency, includeStaged?: boolean): PatchEntry | undefined;
@@ -0,0 +1,68 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import semver from "semver";
4
+ import { fetchJson } from "./http.js";
5
+ import { normalizePyName } from "./osv.js";
6
+ /** Where the public copies live once the repository is published. Overridable for forks and tests. */
7
+ export const REMOTE_REGISTRY_URL = process.env.FOSTER_REGISTRY_URL ?? "https://raw.githubusercontent.com/foster-oss/foster/main/registry/patches.json";
8
+ export const REMOTE_INDEX_URL = process.env.FOSTER_INDEX_URL ?? "https://raw.githubusercontent.com/foster-oss/foster/main/data/orphans.min.json";
9
+ function packageFile(rel) {
10
+ // dist/lib/data.js and src/lib/data.ts are both two levels below the package root
11
+ return fileURLToPath(new URL(`../../${rel}`, import.meta.url));
12
+ }
13
+ function readBundled(rel) {
14
+ const path = packageFile(rel);
15
+ if (!existsSync(path))
16
+ return null;
17
+ return JSON.parse(readFileSync(path, "utf8"));
18
+ }
19
+ async function load(rel, remoteUrl, opts, warnings) {
20
+ if (opts.file)
21
+ return JSON.parse(readFileSync(opts.file, "utf8"));
22
+ if (!opts.offline) {
23
+ try {
24
+ return await fetchJson(remoteUrl, { timeoutMs: 10_000, retries: 0 });
25
+ }
26
+ catch {
27
+ // Fall through to the bundled snapshot. Not a warning: before the repo is public this is expected.
28
+ }
29
+ }
30
+ const bundled = readBundled(rel);
31
+ if (!bundled)
32
+ warnings.push(`no ${rel} available`);
33
+ return bundled;
34
+ }
35
+ export async function loadRegistry(opts = {}, warnings = []) {
36
+ return (await load("registry/patches.json", REMOTE_REGISTRY_URL, opts, warnings)) ?? { version: 1, patches: [] };
37
+ }
38
+ export async function loadOrphanIndex(opts = {}, warnings = []) {
39
+ return ((await load("data/orphans.min.json", REMOTE_INDEX_URL, opts, warnings)) ?? {
40
+ version: 1,
41
+ generatedAt: "",
42
+ source: "none",
43
+ records: [],
44
+ });
45
+ }
46
+ export function indexKey(ecosystem, name) {
47
+ return `${ecosystem}:${ecosystem === "pypi" ? normalizePyName(name) : name}`;
48
+ }
49
+ export function indexByName(file) {
50
+ return new Map(file.records.map((r) => [indexKey(r.ecosystem, r.name), r]));
51
+ }
52
+ /** Find the patch that applies to this exact installed version. */
53
+ export function findPatch(registry, dep, includeStaged = false) {
54
+ return registry.patches.find((p) => {
55
+ if (p.ecosystem !== dep.ecosystem)
56
+ return false;
57
+ if (indexKey(p.ecosystem, p.name) !== indexKey(dep.ecosystem, dep.name))
58
+ return false;
59
+ if (p.status === "retired")
60
+ return false;
61
+ if (p.status === "staged" && !includeStaged)
62
+ return false;
63
+ if (dep.ecosystem === "npm") {
64
+ return semver.valid(dep.version) !== null && semver.satisfies(dep.version, p.affected, { includePrerelease: true });
65
+ }
66
+ return p.affected.split("||").map((s) => s.trim()).includes(dep.version) || p.affected === "*";
67
+ });
68
+ }
@@ -0,0 +1,52 @@
1
+ import type { Ecosystem } from "./types.js";
2
+ /** The subset of the ecosyste.ms package record that Foster relies on. */
3
+ export interface RawAdvisoryPackage {
4
+ ecosystem?: string;
5
+ package_name?: string;
6
+ versions?: {
7
+ first_patched_version?: string | null;
8
+ vulnerable_version_range?: string | null;
9
+ }[];
10
+ }
11
+ export interface RawAdvisory {
12
+ uuid?: string;
13
+ url?: string;
14
+ title?: string;
15
+ severity?: string | null;
16
+ classification?: string | null;
17
+ withdrawn_at?: string | null;
18
+ identifiers?: string[];
19
+ packages?: RawAdvisoryPackage[];
20
+ }
21
+ export interface RawIssueMetadata {
22
+ past_year_issues_count?: number | null;
23
+ past_year_pull_requests_count?: number | null;
24
+ past_year_issues_closed_count?: number | null;
25
+ past_year_pull_requests_closed_count?: number | null;
26
+ past_year_merged_pull_requests_count?: number | null;
27
+ }
28
+ export interface RawRepoMetadata {
29
+ html_url?: string | null;
30
+ archived?: boolean | null;
31
+ pushed_at?: string | null;
32
+ }
33
+ export interface RawPackage {
34
+ name: string;
35
+ ecosystem?: string;
36
+ downloads?: number | null;
37
+ downloads_period?: string | null;
38
+ dependent_repos_count?: number | null;
39
+ dependent_packages_count?: number | null;
40
+ latest_release_number?: string | null;
41
+ latest_release_published_at?: string | null;
42
+ repository_url?: string | null;
43
+ maintainers?: unknown[] | null;
44
+ status?: string | null;
45
+ critical?: boolean | null;
46
+ advisories?: RawAdvisory[] | null;
47
+ repo_metadata?: RawRepoMetadata | null;
48
+ issue_metadata?: RawIssueMetadata | null;
49
+ }
50
+ export declare function getPackage(ecosystem: Ecosystem, name: string): Promise<RawPackage>;
51
+ /** One page of the ecosyste.ms "critical" package set for a registry. Empty array when past the end. */
52
+ export declare function listCriticalPage(ecosystem: Ecosystem, page: number, perPage?: number): Promise<RawPackage[]>;
@@ -0,0 +1,19 @@
1
+ import { fetchJson } from "./http.js";
2
+ const BASE = "https://packages.ecosyste.ms/api/v1";
3
+ const REGISTRY = {
4
+ npm: "npmjs.org",
5
+ pypi: "pypi.org",
6
+ cargo: "crates.io",
7
+ go: "proxy.golang.org",
8
+ rubygems: "rubygems.org",
9
+ packagist: "packagist.org",
10
+ };
11
+ export async function getPackage(ecosystem, name) {
12
+ const url = `${BASE}/registries/${REGISTRY[ecosystem]}/packages/${encodeURIComponent(name)}`;
13
+ return fetchJson(url);
14
+ }
15
+ /** One page of the ecosyste.ms "critical" package set for a registry. Empty array when past the end. */
16
+ export async function listCriticalPage(ecosystem, page, perPage = 100) {
17
+ const url = `${BASE}/registries/${REGISTRY[ecosystem]}/packages?critical=true&per_page=${perPage}&page=${page}`;
18
+ return fetchJson(url, { timeoutMs: 120_000, retries: 4 });
19
+ }
@@ -0,0 +1,38 @@
1
+ import { type NodeManager } from "./lockfile.js";
2
+ import type { Finding } from "./types.js";
3
+ export interface FixChange {
4
+ package: string;
5
+ /** Where the change goes: a dependency field, or the manager's override field. */
6
+ field: string;
7
+ key: string;
8
+ from?: string;
9
+ to: string;
10
+ applied: boolean;
11
+ note?: string;
12
+ }
13
+ export interface FixResult {
14
+ dir: string;
15
+ manager: NodeManager | null;
16
+ changes: FixChange[];
17
+ skipped: {
18
+ package: string;
19
+ reason: string;
20
+ }[];
21
+ written: boolean;
22
+ }
23
+ export interface FixOptions {
24
+ dryRun?: boolean;
25
+ /** Replace an existing, different override for the same package. */
26
+ force?: boolean;
27
+ }
28
+ export declare function detectManager(dir: string): NodeManager | null;
29
+ /**
30
+ * Point every dependency that has a released drop-in patch (Foster or another provider) at the patched package, using an npm alias
31
+ * ("npm:@foster-oss/ip@2.0.1-foster.1"). Code keeps importing the original name; only the bytes change.
32
+ * Direct dependencies are rewritten in place (npm rejects overrides that conflict with direct deps);
33
+ * transitive ones get an override/resolution entry.
34
+ */
35
+ export declare function applyFixes(dirInput: string, findings: Finding[], opts?: FixOptions): FixResult;
36
+ /** Re-serialise JSON keeping the original indentation and trailing newline. */
37
+ export declare function stringifyLike(original: string, value: unknown): string;
38
+ export declare function installCommand(manager: NodeManager | null): string;