@rafter-security/cli 0.10.5 → 0.10.6

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.
@@ -6,7 +6,7 @@ import { SkillManager } from "../../utils/skill-manager.js";
6
6
  import fs from "fs";
7
7
  import path from "path";
8
8
  import os from "os";
9
- import { execSync, spawnSync } from "child_process";
9
+ import { execFileSync, execSync, spawnSync } from "child_process";
10
10
  import { fileURLToPath } from "url";
11
11
  import { createRequire } from "module";
12
12
  import { askYesNo } from "../../utils/prompt.js";
@@ -1041,10 +1041,16 @@ function registerGeminiSkills(skillsDir) {
1041
1041
  if (!fs.existsSync(absPath))
1042
1042
  continue;
1043
1043
  try {
1044
- execSync(`gemini skills link ${JSON.stringify(absPath)}`, {
1045
- stdio: ["ignore", "pipe", "pipe"],
1046
- timeout: 10000,
1047
- });
1044
+ const execOpts = { stdio: ["ignore", "pipe", "pipe"], timeout: 10000 };
1045
+ // No POSIX shell: the path comes from the working directory, whose name
1046
+ // may hold shell syntax. Windows needs cmd.exe to run gemini's .cmd shim,
1047
+ // and cmd.exe treats a double-quoted path literally.
1048
+ if (process.platform === "win32") {
1049
+ execSync(`gemini skills link ${JSON.stringify(absPath)}`, execOpts);
1050
+ }
1051
+ else {
1052
+ execFileSync("gemini", ["skills", "link", absPath], execOpts);
1053
+ }
1048
1054
  console.log(fmt.success(`Registered ${skill.name} with Gemini CLI`));
1049
1055
  }
1050
1056
  catch (e) {
@@ -2,7 +2,7 @@ import { Command } from "commander";
2
2
  import fs from "fs";
3
3
  import os from "os";
4
4
  import path from "path";
5
- import { execSync } from "child_process";
5
+ import { execFileSync, execSync } from "child_process";
6
6
  import { fileURLToPath } from 'url';
7
7
  import { fmt } from "../../utils/formatter.js";
8
8
  const __filename = fileURLToPath(import.meta.url);
@@ -102,7 +102,7 @@ async function installGlobalHook(hookName, templateName) {
102
102
  fs.writeFileSync(hookPath, hookContent, "utf-8");
103
103
  fs.chmodSync(hookPath, 0o755);
104
104
  try {
105
- execSync(`git config --global core.hooksPath "${globalHooksDir}"`, { stdio: "pipe" });
105
+ execFileSync("git", ["config", "--global", "core.hooksPath", globalHooksDir], { stdio: "pipe" });
106
106
  console.log(fmt.success(`Installed Rafter ${hookName} hook globally`));
107
107
  console.log(` Location: ${hookPath}`);
108
108
  console.log(` Git config: core.hooksPath = ${globalHooksDir}`);
@@ -349,6 +349,11 @@ function outputScanResults(results, opts, context, exitOnFindings = true, suppre
349
349
  * Scan files changed since a git ref (+ lines only in the unified diff).
350
350
  */
351
351
  async function scanDiffFiles(ref, opts, scanCfg, baselineEntries = [], scanPath, suppressions = []) {
352
+ // git would parse a leading "-" as one of its own options, not a ref.
353
+ if (ref.startsWith("-")) {
354
+ console.error(`Error: invalid ref "${ref}" (a git ref cannot start with "-")`);
355
+ process.exit(2);
356
+ }
352
357
  await runGitAddedLineScan(["diff", "-U0", "--no-color", "--diff-filter=ACM", ref], opts, scanCfg, baselineEntries, scanPath, suppressions, `files changed since ${ref}`, `No files changed since ${ref}`);
353
358
  }
354
359
  /**
@@ -2,7 +2,7 @@ import { Command } from "commander";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
4
  import os from "os";
5
- import { execSync } from "child_process";
5
+ import { execFileSync, execSync } from "child_process";
6
6
  import { fileURLToPath } from "url";
7
7
  import { getRafterDir, getAuditLogPath, getBinDir } from "../../core/config-defaults.js";
8
8
  import { AuditLogger } from "../../core/audit-logger.js";
@@ -66,7 +66,7 @@ export function createStatusCommand() {
66
66
  catch {
67
67
  if (fs.existsSync(localBetterleaks)) {
68
68
  try {
69
- const ver = execSync(`"${localBetterleaks}" version`, { timeout: 5000, encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"] }).trim();
69
+ const ver = execFileSync(localBetterleaks, ["version"], { timeout: 5000, encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"] }).trim();
70
70
  betterleaksStatus = `${ver} (local)`;
71
71
  }
72
72
  catch {
@@ -1,6 +1,6 @@
1
1
  import { Command } from "commander";
2
2
  import ora from "ora";
3
- import { detectRepo } from "../../utils/git.js";
3
+ import { detectRepo, git, remoteBranchSha } from "../../utils/git.js";
4
4
  import { resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, EXIT_CONFIRMATION_REQUIRED, handle403, apiClient, apiUrl } from "../../utils/api.js";
5
5
  import { ConfigManager } from "../../core/config-manager.js";
6
6
  import { loadPolicy } from "../../core/policy-loader.js";
@@ -68,8 +68,9 @@ export async function runRemoteScan(opts) {
68
68
  const ghToken = opts.githubToken || process.env.RAFTER_GITHUB_TOKEN;
69
69
  let repo, branch;
70
70
  let detectedProvider, detectedRepoUrl;
71
+ let localBranch;
71
72
  try {
72
- ({ repo, branch, provider: detectedProvider, repo_url: detectedRepoUrl } = detectRepo({
73
+ ({ repo, branch, provider: detectedProvider, repo_url: detectedRepoUrl, local_branch: localBranch } = detectRepo({
73
74
  repo: opts.repo,
74
75
  branch: opts.branch,
75
76
  quiet: opts.quiet,
@@ -84,6 +85,28 @@ export async function runRemoteScan(opts) {
84
85
  }
85
86
  process.exit(EXIT_GENERAL_ERROR);
86
87
  }
88
+ // The backend clones the remote, so an auto-detected branch that was never
89
+ // pushed can only fail there. Say so now instead of queueing that scan.
90
+ if (localBranch) {
91
+ const remoteSha = remoteBranchSha(branch);
92
+ if (remoteSha === null) {
93
+ console.error(`Branch "${branch}" does not exist on the remote (origin). Rafter scans the remote ` +
94
+ "repository: push the branch first, or pass --branch to scan one that exists.");
95
+ process.exit(EXIT_GENERAL_ERROR);
96
+ }
97
+ if (remoteSha && !opts.quiet) {
98
+ let head;
99
+ try {
100
+ head = git("rev-parse HEAD");
101
+ }
102
+ catch {
103
+ head = undefined;
104
+ }
105
+ if (head && head !== remoteSha) {
106
+ console.error(`Note: local HEAD differs from origin/${branch}; the scan covers the pushed commit ${remoteSha.slice(0, 7)}.`);
107
+ }
108
+ }
109
+ }
87
110
  // Explicit flags override inferred values.
88
111
  const provider = opts.provider ?? detectedProvider;
89
112
  const repoUrl = opts.repoUrl ?? detectedRepoUrl;
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ import { createSitesCommand } from "./commands/sites/index.js";
23
23
  import { checkForUpdate } from "./utils/update-checker.js";
24
24
  import { setAgentMode } from "./utils/formatter.js";
25
25
  import { createRequire } from "module";
26
- // rf-7dda: a repo `.env` must not be able to disable the hook or its timeouts.
26
+ // A repo `.env` must not be able to set any RAFTER_* variable (key, token, disables).
27
27
  guardSecurityEnvFromDotenv(() => dotenv.config());
28
28
  const require = createRequire(import.meta.url);
29
29
  const { version: VERSION } = require("../package.json");
@@ -1,22 +1,22 @@
1
1
  /**
2
- * Security-control env vars must never be settable by a project `.env`.
2
+ * A project `.env` must never supply a rafter setting.
3
3
  *
4
4
  * `dotenv.config()` runs at CLI startup (index.ts) and, with no path, loads
5
- * `$CWD/.env` — which, when rafter runs inside an agent hook on a cloned repo,
6
- * is a file IN THE UNTRUSTED REPOSITORY. dotenv does not override a variable
7
- * already present in the real environment, but it DOES introduce one that was
8
- * unset — so a repo shipping `RAFTER_DISABLE_HOOKS=1` (or any `RAFTER_DISABLE_*`
9
- * / `RAFTER_HOOK_*` value) could switch off the victim's command policy and
10
- * secret scanning. That defeats the control whose own contract (hook-control.ts)
11
- * says the disable signal is honored only from the machine owner's environment.
5
+ * `$CWD/.env` — which, when rafter runs inside an agent hook or a scan on a
6
+ * cloned repo, is a file IN THE UNTRUSTED REPOSITORY. dotenv does not override
7
+ * a variable already present in the real environment, but it DOES introduce one
8
+ * that was unset. Every `RAFTER_*` variable is an operator setting: the disable
9
+ * switches and hook timeouts, but also the API key (which outranks the key the
10
+ * operator stored in ~/.rafter/config.json), the GitHub token, the notify
11
+ * webhook and the paid-scan confirmation. None of them may come from the repo
12
+ * being scanned.
12
13
  *
13
- * This runs dotenv, then drops any `RAFTER_DISABLE_*` / `RAFTER_HOOK_*` variable
14
- * that was NOT already set in the real environment before dotenv ran. The
15
- * owner's real values are preserved untouched; legitimate `.env` keys that do
16
- * not match those prefixes (RAFTER_API_KEY, RAFTER_GITHUB_TOKEN, …) are
17
- * unaffected. rf-7dda / sable-nz4y sibling.
14
+ * This runs dotenv, then drops any `RAFTER_*` variable that was NOT already set
15
+ * in the real environment before dotenv ran. The owner's real values are
16
+ * preserved untouched. This matches the Python runtime, which never reads the
17
+ * working directory's `.env`.
18
18
  */
19
- const PROTECTED_PREFIX = /^RAFTER_(DISABLE_|HOOK_)/;
19
+ const PROTECTED_PREFIX = /^RAFTER_/;
20
20
  export function guardSecurityEnvFromDotenv(applyDotenv, env = process.env) {
21
21
  const present = new Set();
22
22
  for (const k of Object.keys(env)) {
package/dist/utils/git.js CHANGED
@@ -1,30 +1,113 @@
1
- import { execSync } from "child_process";
1
+ import { execFileSync, execSync } from "child_process";
2
2
  export function git(cmd) {
3
3
  return execSync(`git ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] })
4
4
  .toString()
5
5
  .trim();
6
6
  }
7
+ /**
8
+ * Look up `branch` on the `origin` remote.
9
+ *
10
+ * Returns the remote commit SHA, `null` when the remote answered and has no
11
+ * such branch, or `undefined` when it could not be asked (offline, auth
12
+ * failure, timeout). Callers treat `undefined` as unknown and carry on.
13
+ */
14
+ export function remoteBranchSha(branch, cwd) {
15
+ try {
16
+ const out = execFileSync("git", ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`], {
17
+ cwd,
18
+ stdio: ["ignore", "pipe", "ignore"],
19
+ timeout: 15000,
20
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
21
+ }).toString();
22
+ return out.split(/\s+/)[0] || undefined;
23
+ }
24
+ catch (e) {
25
+ // --exit-code: status 2 means the remote has no matching ref.
26
+ return e?.status === 2 ? null : undefined;
27
+ }
28
+ }
29
+ /**
30
+ * Return the current branch name.
31
+ *
32
+ * Throws on a detached HEAD (or when there is no HEAD at all, e.g. an
33
+ * empty repo) instead of falling back to a commit SHA or a hardcoded
34
+ * default branch. Neither is a real branch: a SHA is guaranteed to 404 as
35
+ * a "branch" on the backend, and a hardcoded default is a guess that is
36
+ * often wrong and, even when right, doesn't reflect what is actually
37
+ * checked out.
38
+ */
7
39
  export function safeBranch(gitFn) {
8
40
  try {
9
41
  return gitFn("symbolic-ref --quiet --short HEAD");
10
42
  }
11
43
  catch {
12
- return gitFn("rev-parse --short HEAD");
44
+ throw new Error("Could not determine the current branch (detached HEAD or no commits yet). " +
45
+ "Please pass --branch explicitly.");
13
46
  }
14
47
  }
15
- export function parseRemote(url) {
16
- url = url.replace(/^(https?:\/\/|git@)/, "").replace(":", "/");
17
- if (url.endsWith(".git"))
18
- url = url.slice(0, -4);
19
- const parts = url.split("/");
20
- return parts.slice(-2).join("/"); // owner/repo
48
+ const SCHEME_RE = /^(https?|ssh):\/\//i;
49
+ /**
50
+ * Split a git remote URL into its host + owner/repo slug, handling
51
+ * `https://[user[:token]@]host[:port]/owner/repo(.git)` (and http, ssh),
52
+ * and the scp-like `[user@]host:owner/repo(.git)`. Returns null when the
53
+ * URL can't be parsed into host + slug.
54
+ *
55
+ * Uses the URL parser (not a blanket ":" -> "/" substitution) so a colon
56
+ * inside userinfo — `https://user:token@host/...`, a real shape for
57
+ * CI-embedded credentials — is never mistaken for the scp host:path
58
+ * separator. Getting this wrong is a security bug, not just a parsing
59
+ * one: the naive substitution let `https://github.com:x@evil.com/a/b`
60
+ * read as host `github.com` (an allowed host) with the real host,
61
+ * evil.com, silently discarded.
62
+ */
63
+ function splitRemote(url) {
64
+ let rest;
65
+ if (SCHEME_RE.test(url)) {
66
+ let parsed;
67
+ try {
68
+ parsed = new URL(url);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ if (!parsed.hostname)
74
+ return null;
75
+ rest = `${parsed.hostname}${parsed.pathname}`;
76
+ }
77
+ else if (url.includes(":")) {
78
+ // scp-like: "[user@]host:owner/repo(.git)". The user (if any) is
79
+ // whatever precedes the LAST "@" before this colon.
80
+ const colonIdx = url.indexOf(":");
81
+ const head = url.slice(0, colonIdx);
82
+ const path = url.slice(colonIdx + 1);
83
+ const atIdx = head.lastIndexOf("@");
84
+ const host = atIdx === -1 ? head : head.slice(atIdx + 1);
85
+ if (!host || host.includes("/"))
86
+ return null;
87
+ rest = `${host}/${path}`;
88
+ }
89
+ else {
90
+ // No scheme, no ":" -- e.g. a bare filesystem path. Treated opaquely:
91
+ // the leading segment stands in for "host" below, so it is rejected
92
+ // unless it happens to equal a real host (it never will for a real
93
+ // filesystem path).
94
+ rest = url;
95
+ }
96
+ if (rest.endsWith(".git"))
97
+ rest = rest.slice(0, -4);
98
+ const parts = rest.split("/").filter((p) => p.length > 0);
99
+ if (parts.length < 3)
100
+ return null; // need host + owner + repo
101
+ const host = parts[0];
102
+ const slug = parts.slice(-2).join("/");
103
+ return { host, slug };
21
104
  }
22
105
  /**
23
- * Map a git remote host to a provider. `github` is the backward-compatible
24
- * default for any host we don't recognize — a GitHub user's request is
25
- * unaffected, and unknown self-hosted hosts fall back to the legacy behavior.
106
+ * Map a git remote host to a provider we actually recognize. Unlike
107
+ * providerForHost, returns null for a host we don't recognize instead of
108
+ * defaulting to "github" — used where guessing is not safe.
26
109
  */
27
- export function providerForHost(host) {
110
+ function knownProviderForHost(host) {
28
111
  host = host.toLowerCase();
29
112
  if (host === "github.com")
30
113
  return "github";
@@ -34,23 +117,41 @@ export function providerForHost(host) {
34
117
  return "bitbucket";
35
118
  if (host === "codeberg.org" || host.endsWith(".gitea.io"))
36
119
  return "gitea";
37
- return "github"; // backward-compatible default
120
+ return null;
38
121
  }
39
122
  /**
40
- * Split a git remote URL into its host + owner/repo slug, handling both
41
- * `git@host:owner/repo(.git)` (scp-like) and `https://host/owner/repo(.git)`.
42
- * Returns null when the URL can't be parsed into host + slug.
123
+ * Parse a git remote URL into "owner/repo" format.
124
+ *
125
+ * Throws when the remote's host isn't one we recognize. Blindly slicing
126
+ * the last two path segments of an arbitrary URL (the old behavior)
127
+ * manufactures a wrong slug for anything that isn't GitHub/GitLab/
128
+ * Bitbucket/Gitea shaped — e.g. an Azure DevOps remote
129
+ * (`.../org/proj/_git/repo`) becomes `_git/repo`, and a bare filesystem
130
+ * remote becomes `<parent-dir>/<repo>`. The backend turns that slug into
131
+ * an invalid clone URL and 404s, burning a paid scan.
43
132
  */
44
- function splitRemote(url) {
45
- let rest = url.replace(/^(https?:\/\/|git@)/, "").replace(":", "/");
46
- if (rest.endsWith(".git"))
47
- rest = rest.slice(0, -4);
48
- const parts = rest.split("/").filter((p) => p.length > 0);
49
- if (parts.length < 3)
50
- return null; // need host + owner + repo
51
- const host = parts[0];
52
- const slug = parts.slice(-2).join("/");
53
- return { host, slug };
133
+ export function parseRemote(url) {
134
+ const parts = splitRemote(url);
135
+ if (!parts) {
136
+ throw new Error(`Could not determine owner/repo from git remote "${url}". ` +
137
+ "Please pass --repo and --branch explicitly.");
138
+ }
139
+ if (!knownProviderForHost(parts.host)) {
140
+ throw new Error(`Unsupported git remote host "${parts.host}" (from "${url}"). ` +
141
+ "Only GitHub, GitLab, Bitbucket, and Gitea remotes are auto-detected. " +
142
+ "Please pass --repo and --branch explicitly.");
143
+ }
144
+ return parts.slug; // owner/repo
145
+ }
146
+ /**
147
+ * Map a git remote host to a provider. `github` is the backward-compatible
148
+ * default for any host we don't recognize — a GitHub user's request is
149
+ * unaffected, and unknown self-hosted hosts fall back to the legacy behavior.
150
+ * (Only used for the additive provider/repoUrl fields; parseRemote uses the
151
+ * stricter knownProviderForHost and rejects what this would silently default.)
152
+ */
153
+ export function providerForHost(host) {
154
+ return knownProviderForHost(host) ?? "github";
54
155
  }
55
156
  /**
56
157
  * Infer the provider and a canonical `https://<host>/<owner>/<repo>` clone URL
@@ -66,6 +167,7 @@ export function inferRemote(url) {
66
167
  repoUrl: `https://${parts.host}/${parts.slug}`,
67
168
  };
68
169
  }
170
+ const AUTO_DETECT_FAILURE = "Could not auto-detect Git repository. Please pass --repo and --branch explicitly.";
69
171
  export function detectRepo(opts) {
70
172
  // Both explicit — return them as-is. No provider/repo_url is inferred here;
71
173
  // the caller's --provider/--repo-url flags fill that in when needed.
@@ -77,35 +179,45 @@ export function detectRepo(opts) {
77
179
  let branch = opts.branch || branchEnv;
78
180
  let provider;
79
181
  let repoUrl;
182
+ if (repoSlug && branch) {
183
+ return { repo: repoSlug, branch, provider, repo_url: repoUrl };
184
+ }
185
+ let insideRepo;
80
186
  try {
81
- if (!repoSlug || !branch) {
82
- if (git("rev-parse --is-inside-work-tree") !== "true")
83
- throw new Error("not a repo");
84
- // Read the remote once when we need to detect the slug, and reuse it to
85
- // infer the provider + canonical clone URL. When repo/branch come from
86
- // env (CI), we never touch git here — behavior is byte-identical.
87
- if (!repoSlug) {
88
- const remoteUrl = git("remote get-url origin");
89
- repoSlug = parseRemote(remoteUrl);
90
- const inferred = inferRemote(remoteUrl);
91
- provider = inferred.provider;
92
- repoUrl = inferred.repoUrl;
93
- }
94
- if (!branch) {
95
- try {
96
- branch = safeBranch(git);
97
- }
98
- catch {
99
- branch = "main";
100
- }
101
- }
187
+ insideRepo = git("rev-parse --is-inside-work-tree") === "true";
188
+ }
189
+ catch {
190
+ insideRepo = false;
191
+ }
192
+ if (!insideRepo) {
193
+ throw new Error(AUTO_DETECT_FAILURE);
194
+ }
195
+ // Read the remote once when we need to detect the slug, and reuse it to
196
+ // infer the provider + canonical clone URL. When repo/branch come from
197
+ // env (CI), we never touch git here — behavior is byte-identical.
198
+ // A rejection from parseRemote (unrecognized host) is deliberately NOT
199
+ // swallowed into the generic message below — it names the offending
200
+ // remote, which is the actionable part.
201
+ const repoFromOrigin = !repoSlug;
202
+ if (!repoSlug) {
203
+ let remoteUrl;
204
+ try {
205
+ remoteUrl = git("remote get-url origin");
102
206
  }
103
- if ((!opts.repo || !opts.branch) && !opts.quiet) {
104
- console.error(`Repo auto-detected: ${repoSlug} @ ${branch} (note: scanning remote)`);
207
+ catch {
208
+ throw new Error(AUTO_DETECT_FAILURE);
105
209
  }
106
- return { repo: repoSlug, branch, provider, repo_url: repoUrl };
210
+ repoSlug = parseRemote(remoteUrl);
211
+ const inferred = inferRemote(remoteUrl);
212
+ provider = inferred.provider;
213
+ repoUrl = inferred.repoUrl;
107
214
  }
108
- catch {
109
- throw new Error("Could not auto-detect Git repository. Please pass --repo and --branch explicitly.");
215
+ const localBranch = repoFromOrigin && !branch;
216
+ if (!branch) {
217
+ branch = safeBranch(git);
218
+ }
219
+ if ((!opts.repo || !opts.branch) && !opts.quiet) {
220
+ console.error(`Repo auto-detected: ${repoSlug} @ ${branch} (note: scanning remote)`);
110
221
  }
222
+ return { repo: repoSlug, branch, provider, repo_url: repoUrl, local_branch: localBranch };
111
223
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.10.5",
3
+ "version": "0.10.6",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rafter-security
3
3
  description: Security toolkit for AI workflows. Use when scanning code or repos for vulnerabilities, auditing third-party skills/MCPs/agent configs before installing, evaluating shell commands before running them, or generating secure design questions for new features. Provides `rafter run` (remote SAST + SCA, needs RAFTER_API_KEY), `rafter secrets` (offline secrets-only), `rafter agent exec --dry-run` (command-risk classification), and `rafter skill review`.
4
- version: 0.10.5
4
+ version: 0.10.6
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw: