@andesyte-oss/cli 0.1.2 → 0.1.4

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.
@@ -0,0 +1,110 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ const execFileAsync = promisify(execFile);
7
+ const SHA_RE = /^[a-f0-9]{40,64}$/;
8
+ export class GitHubPullRequestError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "GitHubPullRequestError";
12
+ }
13
+ }
14
+ function validPullRequestNumber(value) {
15
+ return Number.isSafeInteger(value) && value > 0;
16
+ }
17
+ /** Validates the bounded, structured fields requested from the local gh CLI. */
18
+ export function parseGitHubPullRequest(raw, requestedNumber) {
19
+ if (!validPullRequestNumber(requestedNumber)) {
20
+ throw new GitHubPullRequestError("GitHub pull request number must be a positive integer");
21
+ }
22
+ let value;
23
+ try {
24
+ value = JSON.parse(raw);
25
+ }
26
+ catch {
27
+ throw new GitHubPullRequestError("GitHub CLI returned malformed pull request metadata");
28
+ }
29
+ if (value.number !== requestedNumber) {
30
+ throw new GitHubPullRequestError("GitHub CLI returned metadata for a different pull request");
31
+ }
32
+ if (typeof value.url !== "string" || !/^https:\/\/github\.com\//.test(value.url)) {
33
+ throw new GitHubPullRequestError("GitHub CLI returned an invalid pull request URL");
34
+ }
35
+ if (typeof value.headRefOid !== "string" || !SHA_RE.test(value.headRefOid)) {
36
+ throw new GitHubPullRequestError("GitHub CLI returned an invalid pull request head commit");
37
+ }
38
+ if (typeof value.baseRefOid !== "string" || !SHA_RE.test(value.baseRefOid)) {
39
+ throw new GitHubPullRequestError("GitHub CLI returned an invalid pull request base commit");
40
+ }
41
+ return {
42
+ number: requestedNumber,
43
+ url: value.url,
44
+ headOid: value.headRefOid,
45
+ baseOid: value.baseRefOid,
46
+ };
47
+ }
48
+ async function run(root, command, args) {
49
+ try {
50
+ const { stdout } = await execFileAsync(command, args, {
51
+ cwd: root,
52
+ encoding: "utf8",
53
+ timeout: 120_000,
54
+ maxBuffer: 4 * 1024 * 1024,
55
+ });
56
+ return stdout;
57
+ }
58
+ catch (error) {
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ throw new GitHubPullRequestError(`${command} ${args.join(" ")} failed: ${message}`);
61
+ }
62
+ }
63
+ async function assertCommit(root, oid, label) {
64
+ try {
65
+ await run(root, "git", ["cat-file", "-e", `${oid}^{commit}`]);
66
+ }
67
+ catch {
68
+ throw new GitHubPullRequestError(`GitHub pull request ${label} commit was not fetched`);
69
+ }
70
+ }
71
+ /**
72
+ * Uses the local gh session to resolve a GitHub PR, fetches immutable commits
73
+ * through the repository's existing origin, and removes its detached worktree
74
+ * once the callback settles. It never changes the caller's checkout.
75
+ */
76
+ export async function withGitHubPullRequest(root, number, callback) {
77
+ if (!validPullRequestNumber(number)) {
78
+ throw new GitHubPullRequestError("GitHub pull request number must be a positive integer");
79
+ }
80
+ const metadata = parseGitHubPullRequest(await run(root, "gh", [
81
+ "pr",
82
+ "view",
83
+ String(number),
84
+ "--json",
85
+ "number,url,headRefOid,baseRefOid",
86
+ ]), number);
87
+ await run(root, "git", ["fetch", "--no-tags", "origin", `refs/pull/${number}/head`]);
88
+ await assertCommit(root, metadata.headOid, "head");
89
+ await run(root, "git", ["fetch", "--no-tags", "origin", metadata.baseOid]);
90
+ await assertCommit(root, metadata.baseOid, "base");
91
+ const worktree = await mkdtemp(path.join(tmpdir(), "andesyte-github-pr-"));
92
+ let attached = false;
93
+ try {
94
+ await run(root, "git", ["worktree", "add", "--detach", worktree, metadata.headOid]);
95
+ attached = true;
96
+ return await callback({ ...metadata, root: worktree });
97
+ }
98
+ finally {
99
+ if (attached) {
100
+ try {
101
+ await run(root, "git", ["worktree", "remove", "--force", worktree]);
102
+ }
103
+ catch {
104
+ // The primary scan error remains more useful. Remove the empty worktree
105
+ // directory below even when Git's administrative cleanup fails.
106
+ }
107
+ }
108
+ await rm(worktree, { recursive: true, force: true });
109
+ }
110
+ }
package/dist/index.d.ts CHANGED
@@ -14,9 +14,12 @@ export declare const EXIT_FINDINGS = 1;
14
14
  export declare const EXIT_USAGE = 2;
15
15
  export declare const EXIT_UNTRUSTED = 3;
16
16
  export interface ParsedArgs {
17
- command: "check-code" | "check-dependencies" | "mcp" | "help" | "version";
17
+ command: "check-code" | "check-dependencies" | "doctor" | "mcp" | "skill-path" | "skill-print" | "help" | "version";
18
18
  options: ScanOptions;
19
19
  json: boolean;
20
+ reviewSinks: boolean;
21
+ githubPr?: number;
22
+ checkUpdates: boolean;
20
23
  }
21
24
  export declare class UsageError extends Error {
22
25
  }
@@ -26,11 +29,18 @@ export declare function parseArgs(argv: string[], cwd: string): ParsedArgs;
26
29
  * 0 complete and clean — nothing found, nothing skipped
27
30
  * 1 findings present
28
31
  * 2 invalid invocation
29
- * 3 result not trustworthy: failed, or partial coverage with no findings
32
+ * 3 result not trustworthy: failed or partial
30
33
  *
31
- * A partial scan with no findings must NOT exit 0: it would tell CI "clean"
32
- * when the scanner never looked at part of the change.
34
+ * Findings remain in the output of a partial scan, but the exit code must
35
+ * communicate that the overall result is not trustworthy.
33
36
  */
34
37
  export declare function exitCodeFor(result: ScanResult): number;
38
+ export declare function mcpRootFor(parsed: ParsedArgs): string;
39
+ /**
40
+ * Resolves the packaged skill directory shipped alongside dist/. Not a
41
+ * network fetch and not a copy into the user's project — callers decide
42
+ * whether to symlink, copy, or read it directly.
43
+ */
44
+ export declare function skillDir(): string;
35
45
  export declare function main(argv: string[], cwd: string): Promise<number>;
36
46
  export type { Scope };
package/dist/index.js CHANGED
@@ -8,11 +8,14 @@
8
8
  * 2 invalid invocation (bad flags/args)
9
9
  * 3 scan could not be trusted (engine missing/failed, OSV unavailable)
10
10
  */
11
- import { realpathSync } from "node:fs";
11
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
12
+ import path from "node:path";
12
13
  import { fileURLToPath } from "node:url";
13
- import { SUPPRESSIONS_FILE, applySuppressions, loadSuppressions, scanCode, scanDependencies, } from "@andesyte-oss/scanner-core";
14
- import { rulePaths } from "@andesyte-oss/security-rules";
14
+ import { DEFAULT_LIMITS, } from "@andesyte-oss/scanner-core";
15
+ import { runProjectCheck, suppressionCliReport } from "./checks.js";
16
+ import { collectDoctor, formatDoctor } from "./doctor.js";
15
17
  import { formatHuman, formatJson } from "./format.js";
18
+ import { withGitHubPullRequest } from "./github-pr.js";
16
19
  import { runMcpServer } from "./mcp.js";
17
20
  // Read from package.json rather than a hardcoded literal. A duplicated
18
21
  // version constant silently drifts from the manifest on every release:
@@ -27,19 +30,26 @@ const USAGE = `andesyte ${VERSION} — local security checks for code and depend
27
30
  Usage:
28
31
  andesyte check code [options]
29
32
  andesyte check dependencies [options]
33
+ andesyte doctor [--check-updates] [--json]
34
+ andesyte skill path
35
+ andesyte skill print
30
36
  andesyte mcp
31
37
  andesyte --version
32
38
 
33
39
  Options:
34
40
  --changed Scan changed files (default)
35
41
  --staged Scan staged files only
42
+ --pr <base-ref> Scan commits on HEAD since the PR merge base
43
+ --github-pr <number> Scan a GitHub PR in a temporary detached worktree
36
44
  --all Scan the whole repository
37
45
  --path <p> Scan a specific path (repeatable)
38
46
  --base <ref> Git ref to diff against
39
47
  --json Emit machine-readable JSON
40
- --timeout <ms> Engine deadline (default 30000)
41
- --max-files <n> File cap (default 50)
42
- --max-findings <n> Finding cap (default 20)
48
+ --timeout <ms> Engine deadline (default ${DEFAULT_LIMITS.timeoutMs})
49
+ --max-files <n> File cap (default ${DEFAULT_LIMITS.maxFiles})
50
+ --max-findings <n> Finding cap (default ${DEFAULT_LIMITS.maxFindings})
51
+ --review-sinks Add unknown-origin JS/TS execution and raw-HTML review findings
52
+ --check-updates Query npm for the latest CLI version (doctor only)
43
53
  --cwd <dir> Project root (default: current directory)
44
54
  -h, --help Show this help
45
55
 
@@ -51,7 +61,16 @@ export function parseArgs(argv, cwd) {
51
61
  const base = { root: cwd, scope: "changed" };
52
62
  const paths = [];
53
63
  let json = false;
64
+ let reviewSinks = false;
65
+ let githubPr;
66
+ let checkUpdates = false;
54
67
  let command = null;
68
+ // Tracks whether the caller explicitly requested a scope (as opposed to the
69
+ // "changed" default). --path silently narrowing an unrequested default is
70
+ // fine; --path silently overriding an EXPLICIT --staged/--changed/--all
71
+ // would let a caller believe they got a staged pre-commit check while
72
+ // actually scanning different (working-tree) bytes. Fail closed instead.
73
+ let explicitScope = false;
55
74
  const rest = [...argv];
56
75
  if (rest[0] === "check") {
57
76
  const sub = rest[1];
@@ -67,11 +86,31 @@ export function parseArgs(argv, cwd) {
67
86
  command = "mcp";
68
87
  rest.splice(0, 1);
69
88
  }
89
+ else if (rest[0] === "doctor") {
90
+ command = "doctor";
91
+ rest.splice(0, 1);
92
+ }
93
+ else if (rest[0] === "skill") {
94
+ const sub = rest[1];
95
+ if (sub === "path")
96
+ command = "skill-path";
97
+ else if (sub === "print")
98
+ command = "skill-print";
99
+ else
100
+ throw new UsageError(`unknown skill subcommand: ${sub ?? "(missing)"}`);
101
+ rest.splice(0, 2);
102
+ }
70
103
  else if (rest[0] === "--version" || rest[0] === "-v") {
71
- return { command: "version", options: base, json: false };
104
+ return {
105
+ command: "version",
106
+ options: base,
107
+ json: false,
108
+ reviewSinks: false,
109
+ checkUpdates: false,
110
+ };
72
111
  }
73
112
  else if (rest.length === 0 || rest[0] === "--help" || rest[0] === "-h") {
74
- return { command: "help", options: base, json: false };
113
+ return { command: "help", options: base, json: false, reviewSinks: false, checkUpdates: false };
75
114
  }
76
115
  else {
77
116
  throw new UsageError(`unknown command: ${rest[0]}`);
@@ -81,19 +120,40 @@ export function parseArgs(argv, cwd) {
81
120
  switch (arg) {
82
121
  case "--changed":
83
122
  base.scope = "changed";
123
+ explicitScope = true;
84
124
  break;
85
125
  case "--staged":
86
126
  base.scope = "staged";
127
+ explicitScope = true;
128
+ break;
129
+ case "--pr": {
130
+ const v = rest[++i];
131
+ if (!v)
132
+ throw new UsageError("--pr requires a base ref");
133
+ base.scope = "pull_request";
134
+ base.baseRef = v;
135
+ explicitScope = true;
136
+ break;
137
+ }
138
+ case "--github-pr":
139
+ githubPr = requirePositiveInteger(rest[++i], "--github-pr");
87
140
  break;
88
141
  case "--all":
89
142
  base.scope = "repository";
143
+ explicitScope = true;
90
144
  break;
91
145
  case "--json":
92
146
  json = true;
93
147
  break;
148
+ case "--review-sinks":
149
+ reviewSinks = true;
150
+ break;
151
+ case "--check-updates":
152
+ checkUpdates = true;
153
+ break;
94
154
  case "--help":
95
155
  case "-h":
96
- return { command: "help", options: base, json };
156
+ return { command: "help", options: base, json, reviewSinks, checkUpdates };
97
157
  case "--path": {
98
158
  const v = rest[++i];
99
159
  if (!v)
@@ -129,10 +189,41 @@ export function parseArgs(argv, cwd) {
129
189
  }
130
190
  }
131
191
  if (paths.length > 0) {
192
+ // An explicit --staged/--changed/--all combined with --path is ambiguous:
193
+ // it could mean "restrict that scope to these paths" or it could be a
194
+ // caller mistake that silently switches to working-tree paths scope,
195
+ // scanning different bytes than the requested scope implied (e.g. a
196
+ // pre-commit `--staged` check silently reading unstaged replacements).
197
+ // Reject it rather than guess.
198
+ if (explicitScope) {
199
+ throw new UsageError("--path cannot be combined with --changed, --staged, --pr or --all; use --path alone (working-tree paths scope) or drop --path");
200
+ }
132
201
  base.scope = "paths";
133
202
  base.paths = paths;
134
203
  }
135
- return { command: command, options: base, json };
204
+ if (reviewSinks && command !== "check-code") {
205
+ throw new UsageError("--review-sinks is only valid with `andesyte check code`");
206
+ }
207
+ if (githubPr !== undefined && command === "mcp") {
208
+ throw new UsageError("--github-pr is only valid with `andesyte check code` or `dependencies`");
209
+ }
210
+ if (githubPr !== undefined && (explicitScope || paths.length > 0 || base.root !== cwd)) {
211
+ throw new UsageError("--github-pr cannot be combined with scope, --path, or --cwd options");
212
+ }
213
+ if (checkUpdates && command !== "doctor") {
214
+ throw new UsageError("--check-updates is only valid with `andesyte doctor`");
215
+ }
216
+ if (command === "doctor" && (explicitScope || paths.length > 0 || base.baseRef !== undefined)) {
217
+ throw new UsageError("scan scope, --path, and --base options are not valid with `andesyte doctor`");
218
+ }
219
+ return {
220
+ command: command,
221
+ options: base,
222
+ json,
223
+ reviewSinks,
224
+ githubPr,
225
+ checkUpdates,
226
+ };
136
227
  }
137
228
  function requireNumber(value, flag) {
138
229
  const n = Number(value);
@@ -141,25 +232,41 @@ function requireNumber(value, flag) {
141
232
  }
142
233
  return n;
143
234
  }
235
+ function requirePositiveInteger(value, flag) {
236
+ const n = Number(value);
237
+ if (!value || !Number.isSafeInteger(n) || n < 1) {
238
+ throw new UsageError(`${flag} requires a positive integer`);
239
+ }
240
+ return n;
241
+ }
144
242
  /**
145
243
  * Exit codes:
146
244
  * 0 complete and clean — nothing found, nothing skipped
147
245
  * 1 findings present
148
246
  * 2 invalid invocation
149
- * 3 result not trustworthy: failed, or partial coverage with no findings
247
+ * 3 result not trustworthy: failed or partial
150
248
  *
151
- * A partial scan with no findings must NOT exit 0: it would tell CI "clean"
152
- * when the scanner never looked at part of the change.
249
+ * Findings remain in the output of a partial scan, but the exit code must
250
+ * communicate that the overall result is not trustworthy.
153
251
  */
154
252
  export function exitCodeFor(result) {
155
- if (result.status === "failed")
253
+ if (result.status !== "complete")
156
254
  return EXIT_UNTRUSTED;
157
255
  if (result.findings.length > 0)
158
256
  return EXIT_FINDINGS;
159
- if (result.status === "partial")
160
- return EXIT_UNTRUSTED;
161
257
  return EXIT_OK;
162
258
  }
259
+ export function mcpRootFor(parsed) {
260
+ return parsed.options.root;
261
+ }
262
+ /**
263
+ * Resolves the packaged skill directory shipped alongside dist/. Not a
264
+ * network fetch and not a copy into the user's project — callers decide
265
+ * whether to symlink, copy, or read it directly.
266
+ */
267
+ export function skillDir() {
268
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "skills", "andesyte-code-security");
269
+ }
163
270
  export async function main(argv, cwd) {
164
271
  let parsed;
165
272
  try {
@@ -177,42 +284,49 @@ export async function main(argv, cwd) {
177
284
  process.stdout.write(`${VERSION}\n`);
178
285
  return EXIT_OK;
179
286
  }
287
+ if (parsed.command === "doctor") {
288
+ const report = await collectDoctor(parsed.options.root, { checkUpdates: parsed.checkUpdates });
289
+ process.stdout.write(parsed.json ? `${JSON.stringify(report, null, 2)}\n` : formatDoctor(report));
290
+ return EXIT_OK;
291
+ }
180
292
  if (parsed.command === "mcp") {
181
- await runMcpServer(cwd);
293
+ await runMcpServer(mcpRootFor(parsed));
182
294
  return EXIT_OK;
183
295
  }
184
- const raw = parsed.command === "check-code"
185
- ? await scanCode(parsed.options, { rulePaths: rulePaths() })
186
- : await scanDependencies(parsed.options);
187
- // Suppression is applied to FINDINGS ONLY. It never touches status or
188
- // coverage: accepting a known finding is not the same as having scanned, and
189
- // conflating them would reintroduce the fail-open behaviour this tool exists
190
- // to prevent. A `partial` scan stays `partial` and still exits 3.
191
- const { entries, errors: suppressionErrors } = loadSuppressions(parsed.options.root);
192
- const applied = applySuppressions(raw.findings, entries);
193
- const result = {
194
- ...raw,
195
- findings: applied.kept,
196
- errors: [
197
- ...raw.errors,
198
- // Malformed suppression config is reported, never silently ignored.
199
- ...suppressionErrors.map((message) => ({ code: "parse_failed", message })),
200
- ],
201
- };
202
- process.stdout.write(parsed.json ? formatJson(result) : formatHuman(result));
203
- if (applied.suppressed.length > 0) {
204
- const lines = applied.suppressed
205
- .map((s) => ` ${s.fingerprint} ${s.finding.id} — ${s.reason}\n`)
206
- .join("");
207
- process.stderr.write(`\n${applied.suppressed.length} finding(s) suppressed by ${SUPPRESSIONS_FILE}:\n${lines}`);
296
+ if (parsed.command === "skill-path") {
297
+ const dir = skillDir();
298
+ if (!existsSync(path.join(dir, "SKILL.md"))) {
299
+ process.stderr.write(`andesyte: packaged skill not found at ${dir}\n`);
300
+ return EXIT_UNTRUSTED;
301
+ }
302
+ process.stdout.write(`${dir}\n`);
303
+ return EXIT_OK;
208
304
  }
209
- if (applied.expiredFingerprints.length > 0) {
210
- process.stderr.write(`\n${applied.expiredFingerprints.length} suppression(s) have EXPIRED and were not applied: ${applied.expiredFingerprints.join(", ")}\n`);
305
+ if (parsed.command === "skill-print") {
306
+ const skillFile = path.join(skillDir(), "SKILL.md");
307
+ if (!existsSync(skillFile)) {
308
+ process.stderr.write(`andesyte: packaged skill not found at ${skillFile}\n`);
309
+ return EXIT_UNTRUSTED;
310
+ }
311
+ process.stdout.write(readFileSync(skillFile, "utf8"));
312
+ return EXIT_OK;
211
313
  }
212
- if (applied.unusedFingerprints.length > 0) {
213
- process.stderr.write(`\n${applied.unusedFingerprints.length} suppression(s) matched nothing and can be removed: ${applied.unusedFingerprints.join(", ")}\n`);
314
+ const kind = parsed.command === "check-code" ? "code" : "dependencies";
315
+ const render = async (options, githubPr) => {
316
+ const execution = await runProjectCheck(kind, options, {}, parsed.reviewSinks);
317
+ if (githubPr && execution.result.scope)
318
+ execution.result.scope.github_pull_request = githubPr;
319
+ process.stdout.write(parsed.json ? formatJson(execution.result) : formatHuman(execution.result));
320
+ process.stderr.write(suppressionCliReport(execution.suppression));
321
+ return exitCodeFor(execution.result);
322
+ };
323
+ if (parsed.githubPr !== undefined) {
324
+ return withGitHubPullRequest(parsed.options.root, parsed.githubPr, async (pullRequest) => {
325
+ const { root, ...evidence } = pullRequest;
326
+ return render({ ...parsed.options, root, scope: "pull_request", baseRef: pullRequest.baseOid }, evidence);
327
+ });
214
328
  }
215
- return exitCodeFor(result);
329
+ return render(parsed.options);
216
330
  }
217
331
  /**
218
332
  * npm installs `bin` entries as symlinks (node_modules/.bin/andesyte), so
package/dist/mcp.d.ts CHANGED
@@ -4,20 +4,32 @@
4
4
  * Design constraints:
5
5
  * - Exactly two tools, unbranded names. Clients namespace them themselves
6
6
  * (e.g. `mcp__andesyte__check_code`), so an `andesyte_` prefix would stutter.
7
- * - Brand lives in serverInfo and in `source` on every finding.
7
+ * - Brand lives in package metadata and serverInfo; finding `source` identifies
8
+ * the detection origin (`andesyte` rules or `osv` intelligence).
8
9
  * - Tools accept paths and scope, never source contents.
9
10
  * - stdout carries protocol frames only; all logging goes to stderr.
10
11
  * - No Roots dependency: the project root is fixed at process start.
11
12
  */
12
- import { type ScanResult } from "@andesyte-oss/scanner-core";
13
+ import type { ScanOptions, ScanResult, Scope } from "@andesyte-oss/scanner-core";
13
14
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
15
  import { VERSION as SERVER_VERSION } from "./version.js";
15
16
  export declare const SERVER_NAME = "andesyte-code-security";
16
17
  export { SERVER_VERSION };
18
+ export declare function mcpResultIsError(result: ScanResult): boolean;
17
19
  /**
18
20
  * Agent-facing summary. Deliberately compact: a finding list plus explicit
19
21
  * coverage, so the model can act without re-reading a large envelope.
20
22
  */
21
23
  export declare function summarise(result: ScanResult, kind: "code" | "dependencies"): string;
24
+ /** Thrown when tool input combines an explicit scope with explicit paths ambiguously. */
25
+ export declare class ScopePathConflictError extends Error {
26
+ }
27
+ export declare class PullRequestBaseError extends ScopePathConflictError {
28
+ }
29
+ export declare function buildOptions(root: string, args: {
30
+ scope?: Scope;
31
+ paths?: string[];
32
+ base_ref?: string;
33
+ }): ScanOptions;
22
34
  export declare function createServer(root: string): McpServer;
23
35
  export declare function runMcpServer(root: string): Promise<void>;