@rafter-security/cli 0.7.9 → 0.8.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.
@@ -8,7 +8,26 @@ import { promisify } from "util";
8
8
  import { getBinDir } from "../core/config-defaults.js";
9
9
  import * as tar from "tar";
10
10
  const execAsync = promisify(exec);
11
- export const GITLEAKS_VERSION = "8.18.2";
11
+ export const BETTERLEAKS_VERSION = "1.1.2";
12
+ /**
13
+ * Pinned SHA256 hashes for the bundled BETTERLEAKS_VERSION release artifacts.
14
+ * Pulled from the upstream `checksums.txt` at the time of vendoring; checked into
15
+ * source so we don't trust the release-page `checksums.txt` to authenticate
16
+ * itself when installing the version we ship by default.
17
+ *
18
+ * Whenever you bump BETTERLEAKS_VERSION, refresh these by downloading the new
19
+ * release's `checksums.txt`.
20
+ */
21
+ const BETTERLEAKS_PINNED_HASHES = {
22
+ "betterleaks_1.1.2_darwin_arm64.tar.gz": "19cc2298463d7abf0aee9a03208a49834ab2e6f8411781c4cf1360827b3ded36",
23
+ "betterleaks_1.1.2_darwin_x64.tar.gz": "d51904879ed77fabad157ec67cb8dd3f5548e975fc32082e6abc30a026e1bec1",
24
+ "betterleaks_1.1.2_linux_arm64.tar.gz": "4d73dcbfe38c38878ee69e82b5aaa539398be8331f62b5640eb214ac04d890b0",
25
+ "betterleaks_1.1.2_linux_x64.tar.gz": "648c20617178065072ff1791d383192a62c911d9b4427f0426a8c504a6d9ddad",
26
+ "betterleaks_1.1.2_windows_arm64.zip": "8cc28068e8c7846027bc9b14f1c200cce64ff4198f90be5730510631c59f23ce",
27
+ "betterleaks_1.1.2_windows_x64.zip": "e149c86d00fb99cce8d87def2cd1ff046c6889a0e912007d44668df5980cea3a",
28
+ };
29
+ /** Allowed shape for the optional `--version` flag (prevents URL injection). */
30
+ const VERSION_PATTERN = /^[A-Za-z0-9._-]+$/;
12
31
  export class BinaryManager {
13
32
  constructor() {
14
33
  this.binDir = getBinDir();
@@ -19,13 +38,13 @@ export class BinaryManager {
19
38
  isPlatformSupported() {
20
39
  const platform = process.platform;
21
40
  const arch = process.arch;
22
- // Supported platforms
23
41
  const supported = [
24
42
  "darwin-x64",
25
43
  "darwin-arm64",
26
44
  "linux-x64",
27
45
  "linux-arm64",
28
- "win32-x64"
46
+ "win32-x64",
47
+ "win32-arm64",
29
48
  ];
30
49
  return supported.includes(`${platform}-${arch}`);
31
50
  }
@@ -40,25 +59,42 @@ export class BinaryManager {
40
59
  };
41
60
  }
42
61
  /**
43
- * Get Gitleaks binary path
62
+ * Get Betterleaks binary path
44
63
  */
45
- getGitleaksPath() {
64
+ getBetterleaksPath() {
46
65
  const platform = process.platform;
47
66
  const ext = platform === "win32" ? ".exe" : "";
48
- return path.join(this.binDir, `gitleaks${ext}`);
67
+ return path.join(this.binDir, `betterleaks${ext}`);
49
68
  }
50
69
  /**
51
- * Check if Gitleaks is installed
70
+ * Check if Betterleaks is installed
52
71
  */
53
- isGitleaksInstalled() {
54
- const gitleaksPath = this.getGitleaksPath();
55
- return fs.existsSync(gitleaksPath);
72
+ isBetterleaksInstalled() {
73
+ return fs.existsSync(this.getBetterleaksPath());
56
74
  }
57
75
  /**
58
- * Find gitleaks on system PATH (like Python's shutil.which)
76
+ * Find a leftover legacy gitleaks binary so verify/status can surface
77
+ * an upgrade hint instead of a confusing "not found". PATH first
78
+ * (Homebrew etc.), then ~/.rafter/bin/gitleaks. Read-only — never executes.
59
79
  */
60
- findGitleaksOnPath() {
80
+ findLegacyGitleaks() {
61
81
  const cmd = process.platform === "win32" ? "where gitleaks" : "which gitleaks";
82
+ try {
83
+ const result = execSync(cmd, { timeout: 5000, encoding: "utf-8" });
84
+ const found = result.trim().split("\n")[0].trim();
85
+ if (found)
86
+ return found;
87
+ }
88
+ catch { /* not on PATH */ }
89
+ const ext = process.platform === "win32" ? ".exe" : "";
90
+ const local = path.join(this.binDir, `gitleaks${ext}`);
91
+ return fs.existsSync(local) ? local : null;
92
+ }
93
+ /**
94
+ * Find betterleaks on system PATH
95
+ */
96
+ findBetterleaksOnPath() {
97
+ const cmd = process.platform === "win32" ? "where betterleaks" : "which betterleaks";
62
98
  try {
63
99
  const result = execSync(cmd, { timeout: 5000, encoding: "utf-8" });
64
100
  const found = result.trim().split("\n")[0].trim();
@@ -69,16 +105,14 @@ export class BinaryManager {
69
105
  }
70
106
  }
71
107
  /**
72
- * Verify Gitleaks binary works
108
+ * Verify Betterleaks binary works
73
109
  */
74
- async verifyGitleaks() {
75
- if (!this.isGitleaksInstalled()) {
110
+ async verifyBetterleaks() {
111
+ if (!this.isBetterleaksInstalled()) {
76
112
  return false;
77
113
  }
78
114
  try {
79
- // execAsync rejects on non-zero exit, so reaching here means exit code 0.
80
- // Accept any successful exit — don't require specific stdout content.
81
- await execAsync(`"${this.getGitleaksPath()}" version`, { timeout: 5000 });
115
+ await execAsync(`"${this.getBetterleaksPath()}" version`, { timeout: 5000 });
82
116
  return true;
83
117
  }
84
118
  catch {
@@ -86,14 +120,12 @@ export class BinaryManager {
86
120
  }
87
121
  }
88
122
  /**
89
- * Run gitleaks version and return {ok, stdout, stderr}
123
+ * Run betterleaks version and return {ok, stdout, stderr}
90
124
  */
91
- async verifyGitleaksVerbose(binaryPath) {
92
- const gitleaksPath = binaryPath ?? this.getGitleaksPath();
125
+ async verifyBetterleaksVerbose(binaryPath) {
126
+ const blPath = binaryPath ?? this.getBetterleaksPath();
93
127
  try {
94
- const { stdout, stderr } = await execAsync(`"${gitleaksPath}" version`, { timeout: 5000 });
95
- // execAsync rejects on non-zero exit, so reaching here means exit code 0.
96
- // Accept any successful exit — don't require specific stdout content.
128
+ const { stdout, stderr } = await execAsync(`"${blPath}" version`, { timeout: 5000 });
97
129
  return { ok: true, stdout: stdout.trim(), stderr: stderr.trim() };
98
130
  }
99
131
  catch (e) {
@@ -109,10 +141,10 @@ export class BinaryManager {
109
141
  * Collect diagnostic context for a failed binary (file type, uname, glibc/musl)
110
142
  */
111
143
  async collectBinaryDiagnostics(binaryPath) {
112
- const gitleaksPath = binaryPath ?? this.getGitleaksPath();
144
+ const blPath = binaryPath ?? this.getBetterleaksPath();
113
145
  const lines = [];
114
146
  try {
115
- const { stdout: fileOut } = await execAsync(`file "${gitleaksPath}"`, { timeout: 5000 });
147
+ const { stdout: fileOut } = await execAsync(`file "${blPath}"`, { timeout: 5000 });
116
148
  lines.push(` file: ${fileOut.trim()}`);
117
149
  }
118
150
  catch {
@@ -126,12 +158,11 @@ export class BinaryManager {
126
158
  lines.push(` uname: (unavailable)`);
127
159
  }
128
160
  lines.push(` node arch: ${process.arch}, platform: ${process.platform}`);
129
- // Detect glibc vs musl on Linux
130
161
  if (process.platform === "linux") {
131
162
  try {
132
163
  const { stdout: ldd } = await execAsync("ldd --version 2>&1 || true", { timeout: 5000 });
133
164
  if (ldd.includes("musl")) {
134
- lines.push(" libc: musl (gitleaks linux builds target glibc; musl systems need a musl build or static binary)");
165
+ lines.push(" libc: musl (betterleaks linux builds target glibc; musl systems need a musl build or static binary)");
135
166
  }
136
167
  else if (ldd.includes("GLIBC") || ldd.includes("GNU")) {
137
168
  const match = ldd.match(/(\d+\.\d+)/);
@@ -148,37 +179,32 @@ export class BinaryManager {
148
179
  return lines.join("\n");
149
180
  }
150
181
  /**
151
- * Download and install Gitleaks.
152
- * @param onProgress Optional progress callback.
153
- * @param version Gitleaks version to install (defaults to GITLEAKS_VERSION).
182
+ * Download and install Betterleaks.
154
183
  */
155
- async downloadGitleaks(onProgress, version = GITLEAKS_VERSION) {
184
+ async downloadBetterleaks(onProgress, version = BETTERLEAKS_VERSION) {
156
185
  const log = onProgress || (() => { });
157
- // Check platform support
186
+ if (!VERSION_PATTERN.test(version)) {
187
+ throw new Error(`Invalid betterleaks version: ${version} (expected /^[A-Za-z0-9._-]+$/)`);
188
+ }
158
189
  if (!this.isPlatformSupported()) {
159
- throw new Error(`Gitleaks not available for ${process.platform}/${process.arch}`);
190
+ throw new Error(`Betterleaks not available for ${process.platform}/${process.arch}`);
160
191
  }
161
- // Ensure bin directory exists
162
192
  if (!fs.existsSync(this.binDir)) {
163
193
  fs.mkdirSync(this.binDir, { recursive: true });
164
194
  }
165
195
  const platform = this.getPlatformString();
166
196
  const arch = this.getArchString();
167
197
  const url = this.getDownloadUrl(platform, arch, version);
168
- log(`Downloading Gitleaks v${version} for ${platform}/${arch}...`);
198
+ log(`Downloading Betterleaks v${version} for ${platform}/${arch}...`);
169
199
  log(` URL: ${url}`);
170
- const archivePath = path.join(this.binDir, platform === "windows" ? "gitleaks.zip" : "gitleaks.tar.gz");
200
+ const archivePath = path.join(this.binDir, platform === "windows" ? "betterleaks.zip" : "betterleaks.tar.gz");
171
201
  try {
172
- // Download archive
173
202
  await this.downloadFile(url, archivePath, log);
174
- // Log downloaded file size as basic integrity signal
175
203
  const stats = fs.statSync(archivePath);
176
204
  log(` Downloaded: ${(stats.size / 1024).toFixed(1)} KB`);
177
- // Verify SHA256 checksum against official checksums file
178
205
  log("Verifying checksum...");
179
206
  await this.verifyChecksum(archivePath, platform, arch, version, log);
180
207
  log(" ✓ Checksum verified");
181
- // Extract binary
182
208
  log("Extracting binary...");
183
209
  if (platform === "windows") {
184
210
  await this.extractZip(archivePath);
@@ -186,52 +212,48 @@ export class BinaryManager {
186
212
  else {
187
213
  await this.extractTarball(archivePath);
188
214
  }
189
- // Make executable (Unix systems)
190
215
  if (process.platform !== "win32") {
191
- await execAsync(`chmod +x "${this.getGitleaksPath()}"`);
216
+ await execAsync(`chmod +x "${this.getBetterleaksPath()}"`);
192
217
  log(" chmod +x applied");
193
218
  }
194
- // Verify it works — capture output for diagnostics
195
- const { ok, stdout: verOut, stderr: verErr } = await this.verifyGitleaksVerbose();
219
+ const { ok, stdout: verOut, stderr: verErr } = await this.verifyBetterleaksVerbose();
196
220
  if (!ok) {
197
221
  const diag = await this.collectBinaryDiagnostics();
198
- const binaryPath = this.getGitleaksPath();
199
- throw new Error(`Gitleaks binary failed to execute.\n` +
222
+ const binaryPath = this.getBetterleaksPath();
223
+ throw new Error(`Betterleaks binary failed to execute.\n` +
200
224
  ` Binary: ${binaryPath}\n` +
201
225
  ` URL: ${url}\n` +
202
- (verOut ? ` gitleaks version stdout: ${verOut}\n` : "") +
203
- (verErr ? ` gitleaks version stderr: ${verErr}\n` : "") +
226
+ (verOut ? ` betterleaks version stdout: ${verOut}\n` : "") +
227
+ (verErr ? ` betterleaks version stderr: ${verErr}\n` : "") +
204
228
  `Diagnostics:\n${diag}\n` +
205
- `Fix: ensure the binary matches your OS/arch, or install gitleaks manually and ensure it is on PATH.`);
229
+ `Fix: ensure the binary matches your OS/arch, or install betterleaks manually and ensure it is on PATH.`);
206
230
  }
207
231
  log(` Verified: ${verOut}`);
208
- // Clean up archive
209
232
  if (fs.existsSync(archivePath)) {
210
233
  fs.unlinkSync(archivePath);
211
234
  }
212
- log("✓ Gitleaks installed successfully");
235
+ log("✓ Betterleaks installed successfully");
213
236
  }
214
237
  catch (e) {
215
- // Clean up on failure
216
238
  if (fs.existsSync(archivePath)) {
217
239
  fs.unlinkSync(archivePath);
218
240
  }
219
- const gitleaksPath = this.getGitleaksPath();
220
- if (fs.existsSync(gitleaksPath)) {
221
- fs.unlinkSync(gitleaksPath);
241
+ const blPath = this.getBetterleaksPath();
242
+ if (fs.existsSync(blPath)) {
243
+ fs.unlinkSync(blPath);
222
244
  }
223
245
  throw e;
224
246
  }
225
247
  }
226
248
  /**
227
- * Get Gitleaks version
249
+ * Get Betterleaks version
228
250
  */
229
- async getGitleaksVersion() {
230
- if (!this.isGitleaksInstalled()) {
251
+ async getBetterleaksVersion() {
252
+ if (!this.isBetterleaksInstalled()) {
231
253
  return "not installed";
232
254
  }
233
255
  try {
234
- const { stdout } = await execAsync(`"${this.getGitleaksPath()}" version`);
256
+ const { stdout } = await execAsync(`"${this.getBetterleaksPath()}" version`);
235
257
  return stdout.trim();
236
258
  }
237
259
  catch {
@@ -265,32 +287,59 @@ export class BinaryManager {
265
287
  /**
266
288
  * Get download URL for platform/arch/version
267
289
  */
268
- getDownloadUrl(platform, arch, version = GITLEAKS_VERSION) {
269
- const baseUrl = `https://github.com/gitleaks/gitleaks/releases/download/v${version}`;
290
+ getDownloadUrl(platform, arch, version = BETTERLEAKS_VERSION) {
291
+ const baseUrl = `https://github.com/betterleaks/betterleaks/releases/download/v${version}`;
270
292
  if (platform === "windows") {
271
- return `${baseUrl}/gitleaks_${version}_windows_${arch}.zip`;
293
+ return `${baseUrl}/betterleaks_${version}_windows_${arch}.zip`;
272
294
  }
273
295
  else {
274
- return `${baseUrl}/gitleaks_${version}_${platform}_${arch}.tar.gz`;
296
+ return `${baseUrl}/betterleaks_${version}_${platform}_${arch}.tar.gz`;
275
297
  }
276
298
  }
277
299
  /**
278
- * Download file from URL
300
+ * Download file from URL.
301
+ *
302
+ * Defenses:
303
+ * - HTTPS-only (initial URL and every redirect; non-https rejected)
304
+ * - Redirect cap (max 10 hops; bounds recursion if a CDN misbehaves)
305
+ * - Socket timeout (60s; bounds slow-loris hangs that never close)
306
+ * - Body-size cap (200 MB; bounds DoS-via-large-body if a mirror serves
307
+ * an arbitrarily large stream — betterleaks releases are ~12 MB, so
308
+ * 200 MB has a generous margin while still preventing disk fill)
279
309
  */
280
- downloadFile(url, dest, onProgress) {
310
+ downloadFile(url, dest, onProgress, redirectCount = 0) {
311
+ const MAX_REDIRECTS = 10;
312
+ const MAX_BYTES = 200 * 1024 * 1024;
313
+ const REQUEST_TIMEOUT_MS = 60000;
281
314
  return new Promise((resolve, reject) => {
282
315
  const file = fs.createWriteStream(dest);
283
- https.get(url, (response) => {
284
- // Follow redirects
316
+ const req = https.get(url, (response) => {
317
+ // Follow redirects (HTTPS only — never follow into http://, mailto:, etc.)
285
318
  if (response.statusCode === 302 || response.statusCode === 301) {
319
+ if (redirectCount >= MAX_REDIRECTS) {
320
+ reject(new Error(`Too many redirects (>${MAX_REDIRECTS}) following ${url}`));
321
+ return;
322
+ }
286
323
  const redirectUrl = response.headers.location;
287
324
  if (!redirectUrl) {
288
325
  reject(new Error("Redirect without location"));
289
326
  return;
290
327
  }
328
+ let resolved;
329
+ try {
330
+ resolved = new URL(redirectUrl, url);
331
+ }
332
+ catch {
333
+ reject(new Error(`Invalid redirect URL: ${redirectUrl}`));
334
+ return;
335
+ }
336
+ if (resolved.protocol !== "https:") {
337
+ reject(new Error(`Refusing redirect to non-https URL: ${resolved.toString()}`));
338
+ return;
339
+ }
291
340
  file.close();
292
341
  fs.unlinkSync(dest);
293
- this.downloadFile(redirectUrl, dest, onProgress).then(resolve).catch(reject);
342
+ this.downloadFile(resolved.toString(), dest, onProgress, redirectCount + 1).then(resolve).catch(reject);
294
343
  return;
295
344
  }
296
345
  if (response.statusCode !== 200) {
@@ -298,10 +347,25 @@ export class BinaryManager {
298
347
  return;
299
348
  }
300
349
  const totalBytes = parseInt(response.headers["content-length"] || "0", 10);
350
+ if (totalBytes > MAX_BYTES) {
351
+ reject(new Error(`Download refused: Content-Length ${totalBytes} exceeds cap ${MAX_BYTES} (betterleaks releases are ~12 MB).`));
352
+ response.destroy();
353
+ return;
354
+ }
301
355
  let downloadedBytes = 0;
302
356
  let lastPercent = 0;
303
357
  response.on("data", (chunk) => {
304
358
  downloadedBytes += chunk.length;
359
+ if (downloadedBytes > MAX_BYTES) {
360
+ response.destroy();
361
+ file.close();
362
+ try {
363
+ fs.unlinkSync(dest);
364
+ }
365
+ catch { /* already gone */ }
366
+ reject(new Error(`Download aborted: stream exceeded ${MAX_BYTES} bytes (betterleaks releases are ~12 MB).`));
367
+ return;
368
+ }
305
369
  if (totalBytes > 0) {
306
370
  const percent = Math.round((downloadedBytes / totalBytes) * 100);
307
371
  if (percent > lastPercent && percent % 10 === 0) {
@@ -319,42 +383,65 @@ export class BinaryManager {
319
383
  fs.unlinkSync(dest);
320
384
  reject(err);
321
385
  });
322
- }).on("error", (err) => {
386
+ });
387
+ req.setTimeout(REQUEST_TIMEOUT_MS, () => {
388
+ req.destroy(new Error(`Download timeout after ${REQUEST_TIMEOUT_MS}ms: ${url}`));
389
+ });
390
+ req.on("error", (err) => {
323
391
  if (fs.existsSync(dest)) {
324
- fs.unlinkSync(dest);
392
+ try {
393
+ fs.unlinkSync(dest);
394
+ }
395
+ catch { /* race */ }
325
396
  }
326
397
  reject(err);
327
398
  });
328
399
  });
329
400
  }
330
401
  /**
331
- * Verify downloaded archive checksum against official gitleaks checksums file.
402
+ * Verify downloaded archive checksum.
403
+ *
404
+ * For BETTERLEAKS_VERSION (the version we vendor), use the SHA256 pinned in
405
+ * source — this prevents a release-page compromise from re-signing both the
406
+ * tarball and `checksums.txt`. For an explicit `--version <other>`, fall back
407
+ * to the upstream `checksums.txt` (TOFU at that moment).
332
408
  */
333
- async verifyChecksum(archivePath, platform, arch, version, onProgress) {
334
- const checksumsUrl = `https://github.com/gitleaks/gitleaks/releases/download/v${version}/gitleaks_${version}_checksums.txt`;
335
- const checksumsPath = path.join(this.binDir, "checksums.txt");
336
- try {
337
- await this.downloadFile(checksumsUrl, checksumsPath, () => { });
338
- const checksumsContent = fs.readFileSync(checksumsPath, "utf-8");
339
- const archiveFilename = platform === "windows"
340
- ? `gitleaks_${version}_windows_${arch}.zip`
341
- : `gitleaks_${version}_${platform}_${arch}.tar.gz`;
342
- const expectedHash = this.parseChecksumFile(checksumsContent, archiveFilename);
343
- if (!expectedHash) {
344
- throw new Error(`Checksum not found for ${archiveFilename} in checksums file`);
409
+ async verifyChecksum(archivePath, platform, arch, version, _onProgress) {
410
+ const archiveFilename = platform === "windows"
411
+ ? `betterleaks_${version}_windows_${arch}.zip`
412
+ : `betterleaks_${version}_${platform}_${arch}.tar.gz`;
413
+ let expectedHash = null;
414
+ let source = "";
415
+ if (version === BETTERLEAKS_VERSION && BETTERLEAKS_PINNED_HASHES[archiveFilename]) {
416
+ expectedHash = BETTERLEAKS_PINNED_HASHES[archiveFilename];
417
+ source = "pinned in source";
418
+ }
419
+ else {
420
+ // Fetch the release's `checksums.txt`. This is TOFU — use the pinned table
421
+ // for the bundled default to avoid trusting the release page on every install.
422
+ const checksumsUrl = `https://github.com/betterleaks/betterleaks/releases/download/v${version}/checksums.txt`;
423
+ const checksumsPath = path.join(this.binDir, "checksums.txt");
424
+ try {
425
+ await this.downloadFile(checksumsUrl, checksumsPath, () => { });
426
+ const checksumsContent = fs.readFileSync(checksumsPath, "utf-8");
427
+ expectedHash = this.parseChecksumFile(checksumsContent, archiveFilename);
345
428
  }
346
- const actualHash = await this.computeSHA256(archivePath);
347
- if (actualHash !== expectedHash) {
348
- throw new Error(`Checksum mismatch for ${archiveFilename}:\n` +
349
- ` Expected: ${expectedHash}\n` +
350
- ` Actual: ${actualHash}\n` +
351
- `The downloaded file may be corrupted or tampered with.`);
429
+ finally {
430
+ if (fs.existsSync(checksumsPath)) {
431
+ fs.unlinkSync(checksumsPath);
432
+ }
352
433
  }
434
+ source = "release checksums.txt";
353
435
  }
354
- finally {
355
- if (fs.existsSync(checksumsPath)) {
356
- fs.unlinkSync(checksumsPath);
357
- }
436
+ if (!expectedHash) {
437
+ throw new Error(`Checksum not found for ${archiveFilename} (${source})`);
438
+ }
439
+ const actualHash = await this.computeSHA256(archivePath);
440
+ if (actualHash !== expectedHash) {
441
+ throw new Error(`Checksum mismatch for ${archiveFilename} (${source}):\n` +
442
+ ` Expected: ${expectedHash}\n` +
443
+ ` Actual: ${actualHash}\n` +
444
+ `The downloaded file may be corrupted or tampered with.`);
358
445
  }
359
446
  }
360
447
  /**
@@ -365,7 +452,6 @@ export class BinaryManager {
365
452
  const trimmed = line.trim();
366
453
  if (!trimmed)
367
454
  continue;
368
- // Format: "<sha256> <filename>" (two spaces between hash and filename)
369
455
  const parts = trimmed.split(/\s+/);
370
456
  if (parts.length >= 2 && parts[1] === filename) {
371
457
  return parts[0].toLowerCase();
@@ -387,21 +473,18 @@ export class BinaryManager {
387
473
  }
388
474
  /**
389
475
  * Extract zip (Windows) — uses PowerShell's Expand-Archive, then copies
390
- * only the gitleaks.exe binary to binDir. Cleans up the temp extract dir.
476
+ * only the betterleaks.exe binary to binDir. Cleans up the temp extract dir.
391
477
  */
392
478
  async extractZip(zipPath) {
393
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "rafter-gitleaks-"));
479
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "rafter-betterleaks-"));
394
480
  try {
395
- // PowerShell 5+ ships on all supported Windows versions
396
- // Escape single quotes to prevent shell injection ('' is the PS escape for ')
397
481
  const safeZipPath = zipPath.replace(/'/g, "''");
398
482
  const safeTempDir = tempDir.replace(/'/g, "''");
399
483
  await execAsync(`powershell -NoProfile -Command "Expand-Archive -Force -LiteralPath '${safeZipPath}' -DestinationPath '${safeTempDir}'"`, { timeout: 30000 });
400
- // Find gitleaks.exe — may be at root or inside a subdirectory
401
484
  const findBinary = (dir) => {
402
485
  for (const entry of fs.readdirSync(dir)) {
403
486
  const full = path.join(dir, entry);
404
- if (entry === "gitleaks.exe")
487
+ if (entry === "betterleaks.exe")
405
488
  return full;
406
489
  if (fs.statSync(full).isDirectory()) {
407
490
  const found = findBinary(full);
@@ -413,8 +496,8 @@ export class BinaryManager {
413
496
  };
414
497
  const found = findBinary(tempDir);
415
498
  if (!found)
416
- throw new Error("gitleaks.exe not found in archive");
417
- fs.copyFileSync(found, path.join(this.binDir, "gitleaks.exe"));
499
+ throw new Error("betterleaks.exe not found in archive");
500
+ fs.copyFileSync(found, path.join(this.binDir, "betterleaks.exe"));
418
501
  }
419
502
  finally {
420
503
  fs.rmSync(tempDir, { recursive: true, force: true });
@@ -423,19 +506,32 @@ export class BinaryManager {
423
506
  /**
424
507
  * Extract tarball — binary only, strip packaging extras (LICENSE, README.md).
425
508
  *
426
- * The gitleaks release tarball has all files at the archive root (no top-level
427
- * directory), so strip: 0 (the default). With strip: 1, node-tar reduces the
428
- * single-component paths to empty strings; the filter never matches "gitleaks"
429
- * and nothing is extracted. The filter alone is sufficient.
509
+ * Rejects symlinks, hardlinks, and absolute / `..` paths defensively. node-tar
510
+ * blocks `..`/absolute by default, but symlinks/hardlinks would otherwise pass
511
+ * the basename filter and let a malicious release point `betterleaks` at e.g.
512
+ * `~/.ssh/authorized_keys`, which the subsequent `chmod +x` would then mode-flip.
430
513
  */
431
514
  async extractTarball(tarballPath) {
432
515
  await tar.extract({
433
516
  file: tarballPath,
434
517
  cwd: this.binDir,
435
- filter: (p) => {
518
+ filter: (p, entry) => {
436
519
  const base = path.basename(p);
437
- return base === "gitleaks" || base === "gitleaks.exe";
520
+ if (base !== "betterleaks" && base !== "betterleaks.exe")
521
+ return false;
522
+ if (entry?.type && entry.type !== "File")
523
+ return false;
524
+ return true;
438
525
  },
439
526
  });
527
+ // Post-extract belt-and-suspenders: ensure what landed is a regular file.
528
+ const installedPath = this.getBetterleaksPath();
529
+ if (fs.existsSync(installedPath)) {
530
+ const st = fs.lstatSync(installedPath);
531
+ if (!st.isFile() || st.isSymbolicLink()) {
532
+ fs.unlinkSync(installedPath);
533
+ throw new Error("Extracted betterleaks is not a regular file (symlink or special); aborting.");
534
+ }
535
+ }
440
536
  }
441
537
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.7.9",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "rafter": "./dist/index.js"
@@ -22,7 +22,7 @@ Rafter ships three CLI tiers **and** four in-repo skills. They are NOT interchan
22
22
 
23
23
  1. **`rafter run`** (default mode) — remote SAST + SCA + secrets via the Rafter API. Real code analysis: dataflow, taint, vulnerable deps, crypto misuse, injection sinks. Needs `RAFTER_API_KEY`. **This is the default for "is this safe / secure / production worthy?".**
24
24
  2. **`rafter run --mode plus`** — agentic deep-dive on suspicious patterns. Slower, higher signal. Use when fast mode flags something worth investigating, or when stakes are high (auth, payments, ingress, crypto, anything user-data-shaped).
25
- 3. **`rafter secrets [path]`** — local secrets only (regex + gitleaks for hardcoded API keys, tokens, private keys). Fast, offline, no key. **NOT a code security scan.** Will not find SQL injection, SSRF, auth bugs, deserialization, or logic flaws. Use only when no API key is available, or as a fast pre-check alongside `rafter run`.
25
+ 3. **`rafter secrets [path]`** — local secrets only (regex + betterleaks for hardcoded API keys, tokens, private keys). Fast, offline, no key. **NOT a code security scan.** Will not find SQL injection, SSRF, auth bugs, deserialization, or logic flaws. Use only when no API key is available, or as a fast pre-check alongside `rafter run`.
26
26
 
27
27
  If `RAFTER_API_KEY` is unset, run `rafter secrets` and **say so explicitly in your verdict** — "secrets-only pass; full code analysis was skipped (no API key)." Do not claim the code was "scanned" without that qualification. Never silently downgrade.
28
28
 
@@ -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.7.9
4
+ version: 0.8.0
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw:
@@ -40,7 +40,7 @@ To initialize Rafter, use **opt-in** `--with-*` flags to select integrations. Th
40
40
  ```bash
41
41
  # Install specific integrations (opt-in)
42
42
  rafter agent init --with-openclaw
43
- rafter agent init --with-claude-code --with-gitleaks
43
+ rafter agent init --with-claude-code --with-betterleaks
44
44
 
45
45
  # Install everything detected
46
46
  rafter agent init --all
@@ -11,7 +11,7 @@ allowed-tools: [Bash, Read]
11
11
 
12
12
  Rafter ships three tiers. **They are not interchangeable.** The local tier is narrow; skipping remote analysis is the #1 way agents under-use rafter.
13
13
 
14
- 1. **Local (`rafter secrets`)** — secrets only. Regex + gitleaks for hardcoded API keys, tokens, private keys. Fast, offline, no key. **This is NOT a code security scan.** It will not find SQL injection, SSRF, auth bugs, insecure deserialization, logic flaws, or dependency vulns. If an agent's entire rafter interaction was `rafter secrets .` and it exited clean, the agent has done secret-hygiene only — not security review.
14
+ 1. **Local (`rafter secrets`)** — secrets only. Regex + betterleaks for hardcoded API keys, tokens, private keys. Fast, offline, no key. **This is NOT a code security scan.** It will not find SQL injection, SSRF, auth bugs, insecure deserialization, logic flaws, or dependency vulns. If an agent's entire rafter interaction was `rafter secrets .` and it exited clean, the agent has done secret-hygiene only — not security review.
15
15
  2. **Remote fast (`rafter run`, default mode)** — SAST + SCA + secrets via the Rafter API. This is the real code-analysis pass: dataflow, taint, known-vulnerable dependencies, crypto misuse, injection sinks. Needs `RAFTER_API_KEY`.
16
16
  3. **Remote plus (`rafter run --mode plus`)** — agentic deep-dive: LLM-guided investigation of suspicious patterns the rules engine flags. Slower, higher signal. Code is deleted server-side after the run.
17
17
 
@@ -32,11 +32,11 @@ Example: `rafter run --repo myorg/api --branch feature/auth --mode plus --format
32
32
 
33
33
  ### `rafter secrets [path]`
34
34
 
35
- Local secret scan. Deterministic, offline, no API key. Dual-engine: Gitleaks binary if present, built-in regex fallback (21+ patterns).
35
+ Local secret scan. Deterministic, offline, no API key. Dual-engine: Betterleaks binary if present, built-in regex fallback (21+ patterns).
36
36
 
37
37
  When: pre-commit, pre-push, fast first pass before remote scan, air-gapped envs.
38
38
 
39
- Useful flags: `--history` (scan git history with Gitleaks), `--format json`, `--quiet`.
39
+ Useful flags: `--history` (scan git history with Betterleaks), `--format json`, `--quiet`.
40
40
 
41
41
  Example: `rafter secrets . --format json`
42
42
 
@@ -80,7 +80,7 @@ Audit a single skill file (SKILL.md). Flags prompt-injection, unbounded tool use
80
80
 
81
81
  ### `rafter agent status` · `rafter agent verify`
82
82
 
83
- `status`: dump config, hook state, gitleaks availability, audit log location.
83
+ `status`: dump config, hook state, betterleaks availability, audit log location.
84
84
  `verify`: sanity-check installation; exit non-zero if anything is broken.
85
85
 
86
86
  ### `rafter agent init [--with-<platform>]`
@@ -107,9 +107,9 @@ Snapshot current findings so only *new* ones fail future scans.
107
107
 
108
108
  Emit a ready-to-paste instruction block for an agent's system prompt.
109
109
 
110
- ### `rafter agent update-gitleaks`
110
+ ### `rafter agent update-betterleaks`
111
111
 
112
- Download / upgrade the Gitleaks binary Rafter uses for local scans.
112
+ Download / upgrade the Betterleaks binary Rafter uses for local scans.
113
113
 
114
114
  ---
115
115