leakshield 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +546 -2
- package/README.zh-TW.md +565 -0
- package/dist/cli.js +61 -0
- package/dist/config/loader.js +94 -0
- package/dist/decision/deidentify.js +195 -0
- package/dist/decision/ingress.js +136 -0
- package/dist/decision/mapping-key.js +318 -0
- package/dist/decision/mapping-store.js +555 -0
- package/dist/decision/model.js +76 -0
- package/dist/decision/pseudonymization.js +1230 -0
- package/dist/decision/redaction.js +185 -0
- package/dist/decision/schema-strings.js +42 -0
- package/dist/doctor.js +438 -0
- package/dist/env-queries.js +584 -0
- package/dist/forget.js +56 -0
- package/dist/help.js +37 -0
- package/dist/i18n/en.js +71 -0
- package/dist/i18n/index.js +28 -0
- package/dist/i18n/zh-TW.js +71 -0
- package/dist/index.js +12 -0
- package/dist/opencode-env-tools.js +243 -0
- package/dist/opencode-hooks.js +84 -0
- package/dist/opencode-transparent-aisdk.js +100 -0
- package/dist/opencode-transparent-http.js +2315 -0
- package/dist/opencode-transparent-stream.js +192 -0
- package/dist/opencode-transparent-ws.js +298 -0
- package/dist/opencode-transparent.js +1492 -0
- package/dist/opencode-v2.js +216 -0
- package/dist/opencode.js +175 -0
- package/dist/plugin-options.js +100 -0
- package/dist/rules/builtin.js +283 -0
- package/dist/rules/dynamic.js +68 -0
- package/dist/scanner/encoding.js +274 -0
- package/dist/scanner/engine.js +321 -0
- package/dist/scanner/exact-values.js +99 -0
- package/dist/scanner/redaction-verifier.js +82 -0
- package/dist/scanner/unicode.js +157 -0
- package/dist/scanner/utils.js +60 -0
- package/dist/transports/cli.js +447 -0
- package/dist/transports/web-ui.js +540 -0
- package/dist/transports/web.js +200 -0
- package/dist/types.js +23 -0
- package/dist/utils/files.js +36 -0
- package/dist/utils/path-security.js +30 -0
- package/dist/utils/win-encoding.js +45 -0
- package/package.json +71 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Redact a matched secret for safe display.
|
|
2
|
+
// SECURITY: Regardless of value length or previewLen, we always return "****"
|
|
3
|
+
// to prevent any partial secret exposure in output (previews, logs, reports).
|
|
4
|
+
// The _value and _previewLen parameters are retained for API compatibility.
|
|
5
|
+
export function redact(_value, _previewLen) {
|
|
6
|
+
return "****";
|
|
7
|
+
}
|
|
8
|
+
export function getLineCol(text, index) {
|
|
9
|
+
const before = text.slice(0, index);
|
|
10
|
+
const lines = before.split(/\r?\n/);
|
|
11
|
+
return { line: lines.length, col: lines[lines.length - 1].length + 1 };
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Multiple ignore patterns to prevent bypass attempts.
|
|
15
|
+
*
|
|
16
|
+
* Supported formats:
|
|
17
|
+
* - // leakshield-ignore
|
|
18
|
+
* - // guard:skip
|
|
19
|
+
* - // guard:ignore
|
|
20
|
+
* - // sg-ignore
|
|
21
|
+
* - // no-scan
|
|
22
|
+
* - // skip-guard
|
|
23
|
+
*
|
|
24
|
+
* All patterns are word-boundary protected to prevent:
|
|
25
|
+
* - leakshield-ignored (won't match)
|
|
26
|
+
* - leakshield_ignore (won't match)
|
|
27
|
+
* - leakshieldignore (won't match)
|
|
28
|
+
*/
|
|
29
|
+
const IGNORE_PATTERNS = [
|
|
30
|
+
/\bleakshield-ignore\b/i, // Original format
|
|
31
|
+
/\bguard:\s*skip\b/i, // Short format
|
|
32
|
+
/\bguard:\s*ignore\b/i, // Short format alternative
|
|
33
|
+
/\bsg-ignore\b/i, // Abbreviated
|
|
34
|
+
/\bno-scan\b/i, // Alternative
|
|
35
|
+
/\bskip-guard\b/i, // Alternative
|
|
36
|
+
];
|
|
37
|
+
/**
|
|
38
|
+
* Extracts line numbers that should be ignored during scanning.
|
|
39
|
+
*
|
|
40
|
+
* Lines containing any of the supported ignore patterns will be skipped.
|
|
41
|
+
* This prevents attackers from using variants to bypass detection.
|
|
42
|
+
*
|
|
43
|
+
* @param text - The full text content to scan
|
|
44
|
+
* @returns Set of line numbers (1-indexed) to ignore
|
|
45
|
+
*/
|
|
46
|
+
export function getIgnoredLines(text) {
|
|
47
|
+
const ignored = new Set();
|
|
48
|
+
const lines = text.split(/\r?\n/);
|
|
49
|
+
for (let i = 0; i < lines.length; i++) {
|
|
50
|
+
const line = lines[i];
|
|
51
|
+
// Check against all patterns
|
|
52
|
+
for (const pattern of IGNORE_PATTERNS) {
|
|
53
|
+
if (pattern.test(line)) {
|
|
54
|
+
ignored.add(i + 1); // 1-indexed
|
|
55
|
+
break; // No need to check other patterns for this line
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return ignored;
|
|
60
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import chalk from "chalk";
|
|
4
|
+
import { loadConfig } from "../config/loader.js";
|
|
5
|
+
import { scanText, redactText } from "../scanner/engine.js";
|
|
6
|
+
import { redactAndVerify } from "../scanner/redaction-verifier.js";
|
|
7
|
+
import { sanitizeRedactResultForExport } from "../decision/redaction.js";
|
|
8
|
+
import { toDecisionResult } from "../decision/model.js";
|
|
9
|
+
import { collectFiles, runWithConcurrency } from "../utils/files.js";
|
|
10
|
+
import { validateCliScanPath } from "../utils/path-security.js";
|
|
11
|
+
import { t } from "../i18n/index.js";
|
|
12
|
+
import { initWindowsEncoding, readFileWithEncoding } from "../utils/win-encoding.js";
|
|
13
|
+
export { validateCliScanPath };
|
|
14
|
+
const SCAN_CONCURRENCY = 8;
|
|
15
|
+
// ─── Severity filter ─────────────────────────────────────────────────────────
|
|
16
|
+
const SEVERITY_RANK = { HIGH: 3, MEDIUM: 2, LOW: 1 };
|
|
17
|
+
export function filterBySeverity(result, min) {
|
|
18
|
+
const threshold = SEVERITY_RANK[min.toUpperCase()];
|
|
19
|
+
const findings = result.findings.filter((f) => SEVERITY_RANK[f.severity] >= threshold);
|
|
20
|
+
const safe = findings.length === 0;
|
|
21
|
+
const highCount = findings.filter((f) => f.severity === "HIGH").length;
|
|
22
|
+
const medCount = findings.filter((f) => f.severity === "MEDIUM").length;
|
|
23
|
+
const summary = safe
|
|
24
|
+
? t("scan.safe_summary")
|
|
25
|
+
: t("scan.unsafe_summary", {
|
|
26
|
+
count: findings.length,
|
|
27
|
+
high: highCount,
|
|
28
|
+
med: medCount,
|
|
29
|
+
low: findings.length - highCount - medCount,
|
|
30
|
+
});
|
|
31
|
+
return { ...result, findings, total_findings: findings.length, safe, summary };
|
|
32
|
+
}
|
|
33
|
+
// ─── Decision-aware CLI formatting ──────────────────────────────────────────
|
|
34
|
+
const SEPARATOR = "─".repeat(60);
|
|
35
|
+
/**
|
|
36
|
+
* Pure function that formats a GuardDecisionResult into CLI output lines.
|
|
37
|
+
*
|
|
38
|
+
* Does NOT write to console — returns an array of strings so callers can
|
|
39
|
+
* test formatting without capturing stdout.
|
|
40
|
+
*
|
|
41
|
+
* | decision | Behaviour |
|
|
42
|
+
* |----------|---------------------------------------------|
|
|
43
|
+
* | ALLOW | Clean summary, continue normally |
|
|
44
|
+
* | WARN | Reminder with findings, then continue |
|
|
45
|
+
* | CONFIRM | Warning card with actions (non-interactive) |
|
|
46
|
+
*/
|
|
47
|
+
export function formatCliDecision(decision, label) {
|
|
48
|
+
const lines = [];
|
|
49
|
+
lines.push("");
|
|
50
|
+
lines.push(chalk.bold(t("cli.scan_target", { label })));
|
|
51
|
+
lines.push(SEPARATOR);
|
|
52
|
+
const DECISION_COLOR = {
|
|
53
|
+
ALLOW: chalk.green,
|
|
54
|
+
WARN: chalk.yellow,
|
|
55
|
+
CONFIRM: chalk.red,
|
|
56
|
+
};
|
|
57
|
+
const colorFn = DECISION_COLOR[decision.decision] ?? ((s) => s);
|
|
58
|
+
if (decision.decision === "ALLOW") {
|
|
59
|
+
lines.push(colorFn(t("scan.safe_summary")));
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
// Decision + Risk title line
|
|
63
|
+
const actionPart = decision.recommendedAction
|
|
64
|
+
? ` | Action: ${decision.recommendedAction}`
|
|
65
|
+
: "";
|
|
66
|
+
lines.push(colorFn(`Decision: ${decision.decision} | Risk: ${decision.riskLevel}${actionPart}`));
|
|
67
|
+
lines.push(decision.summary);
|
|
68
|
+
lines.push("");
|
|
69
|
+
// Group findings by type
|
|
70
|
+
const byType = {};
|
|
71
|
+
for (const f of decision.findings) {
|
|
72
|
+
if (!byType[f.type])
|
|
73
|
+
byType[f.type] = [];
|
|
74
|
+
byType[f.type].push(f);
|
|
75
|
+
}
|
|
76
|
+
for (const [type, items] of Object.entries(byType)) {
|
|
77
|
+
if (!items)
|
|
78
|
+
continue;
|
|
79
|
+
const severity = items[0].severity;
|
|
80
|
+
const color = severity === "HIGH" ? chalk.red : severity === "MEDIUM" ? chalk.yellow : chalk.gray;
|
|
81
|
+
lines.push(color(` [${severity}] ${type} — ${t("cli.hits", { count: items.length })}`));
|
|
82
|
+
for (const item of items.slice(0, 5)) {
|
|
83
|
+
const loc = item.line
|
|
84
|
+
? chalk.dim(` (line ${item.line})`)
|
|
85
|
+
: "";
|
|
86
|
+
lines.push(` • ${item.description}${loc}`);
|
|
87
|
+
lines.push(chalk.dim(t("cli.preview", { preview: item.preview })));
|
|
88
|
+
}
|
|
89
|
+
if (items.length > 5) {
|
|
90
|
+
lines.push(chalk.dim(t("cli.more_of_type", { count: items.length - 5 })));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// CONFIRM: next step hint
|
|
94
|
+
if (decision.decision === "CONFIRM") {
|
|
95
|
+
lines.push("");
|
|
96
|
+
lines.push(chalk.dim(`💡 ${t("cli.confirm_next_step")}`));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
lines.push("");
|
|
100
|
+
lines.push(SEPARATOR);
|
|
101
|
+
lines.push("");
|
|
102
|
+
return lines;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Build a decision-oriented JSON object safe for CLI/CI export.
|
|
106
|
+
*
|
|
107
|
+
* Strips `originalContent` and ensures findings carry only transport-safe fields.
|
|
108
|
+
*/
|
|
109
|
+
export function buildDecisionJsonOutput(decision, label) {
|
|
110
|
+
const { originalContent: _oc, ...safeDecision } = decision;
|
|
111
|
+
return {
|
|
112
|
+
label,
|
|
113
|
+
safe: safeDecision.decision === "ALLOW",
|
|
114
|
+
decision: safeDecision.decision,
|
|
115
|
+
riskLevel: safeDecision.riskLevel,
|
|
116
|
+
summary: safeDecision.summary,
|
|
117
|
+
findings: safeDecision.findings.map((f) => ({
|
|
118
|
+
type: f.type,
|
|
119
|
+
severity: f.severity,
|
|
120
|
+
description: f.description,
|
|
121
|
+
preview: f.preview,
|
|
122
|
+
...(f.line !== undefined ? { line: f.line } : {}),
|
|
123
|
+
})),
|
|
124
|
+
...(safeDecision.recommendedAction !== undefined
|
|
125
|
+
? { recommendedAction: safeDecision.recommendedAction }
|
|
126
|
+
: {}),
|
|
127
|
+
...(safeDecision.safePreview !== undefined
|
|
128
|
+
? { safePreview: safeDecision.safePreview }
|
|
129
|
+
: {}),
|
|
130
|
+
...(safeDecision.redactedContent !== undefined
|
|
131
|
+
? { redactedContent: safeDecision.redactedContent }
|
|
132
|
+
: {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Print decision-aware output to console (text mode).
|
|
137
|
+
*/
|
|
138
|
+
function printCliDecision(decision, label) {
|
|
139
|
+
const lines = formatCliDecision(decision, label);
|
|
140
|
+
for (const line of lines) {
|
|
141
|
+
console.log(line);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// ─── Text output ─────────────────────────────────────────────────────────────
|
|
145
|
+
export function printCliResult(result, label) {
|
|
146
|
+
console.log("");
|
|
147
|
+
console.log(chalk.bold(t("cli.scan_target", { label })));
|
|
148
|
+
console.log("─".repeat(60));
|
|
149
|
+
if (result.safe) {
|
|
150
|
+
console.log(chalk.green(result.summary));
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
console.log(chalk.red(result.summary));
|
|
154
|
+
console.log("");
|
|
155
|
+
const byType = {};
|
|
156
|
+
for (const f of result.findings) {
|
|
157
|
+
if (!byType[f.type])
|
|
158
|
+
byType[f.type] = [];
|
|
159
|
+
byType[f.type].push(f);
|
|
160
|
+
}
|
|
161
|
+
for (const [type, items] of Object.entries(byType)) {
|
|
162
|
+
const severity = items[0].severity;
|
|
163
|
+
const color = severity === "HIGH" ? chalk.red : severity === "MEDIUM" ? chalk.yellow : chalk.gray;
|
|
164
|
+
console.log(color(`\n [${severity}] ${type} — ${t("cli.hits", { count: items.length })}`));
|
|
165
|
+
for (const item of items.slice(0, 5)) {
|
|
166
|
+
const loc = item.line
|
|
167
|
+
? chalk.dim(t("cli.location", { line: item.line, col: item.column ?? 0 }))
|
|
168
|
+
: "";
|
|
169
|
+
console.log(` • ${item.description}${loc}`);
|
|
170
|
+
console.log(chalk.dim(t("cli.preview", { preview: item.preview })));
|
|
171
|
+
}
|
|
172
|
+
if (items.length > 5) {
|
|
173
|
+
console.log(chalk.dim(t("cli.more_of_type", { count: items.length - 5 })));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
console.log("");
|
|
178
|
+
console.log(result.safe ? chalk.green("💡 " + result.recommendation) : chalk.red("⚠️ " + result.recommendation));
|
|
179
|
+
console.log("─".repeat(60));
|
|
180
|
+
console.log("");
|
|
181
|
+
}
|
|
182
|
+
// ─── CLI entry ───────────────────────────────────────────────────────────────
|
|
183
|
+
export async function runCli() {
|
|
184
|
+
initWindowsEncoding();
|
|
185
|
+
const args = process.argv.slice(2);
|
|
186
|
+
let config = loadConfig();
|
|
187
|
+
const textIdx = args.indexOf("--text");
|
|
188
|
+
const fileIdx = args.indexOf("--file");
|
|
189
|
+
const dirIdx = args.indexOf("--dir");
|
|
190
|
+
const extIdx = args.indexOf("--ext");
|
|
191
|
+
const fmtIdx = args.indexOf("--format");
|
|
192
|
+
const sevIdx = args.indexOf("--min-severity");
|
|
193
|
+
const outIdx = args.indexOf("--out");
|
|
194
|
+
const stdinMode = args.includes("--stdin");
|
|
195
|
+
const redactMode = args.includes("--redact");
|
|
196
|
+
const dryRun = args.includes("--dry-run");
|
|
197
|
+
const encodingDetection = args.includes("--enable-encoding-detection");
|
|
198
|
+
// Override config if flag is provided
|
|
199
|
+
if (encodingDetection) {
|
|
200
|
+
config = {
|
|
201
|
+
...config,
|
|
202
|
+
settings: {
|
|
203
|
+
...config.settings,
|
|
204
|
+
encoding_detection: true,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const format = args[fmtIdx + 1] === "json" ? "json" : "text";
|
|
209
|
+
const minSeverity = (["high", "medium", "low"].includes(args[sevIdx + 1]) ? args[sevIdx + 1] : "low");
|
|
210
|
+
const allowOutside = args.includes("--allow-outside");
|
|
211
|
+
function output(result, label, originalContent) {
|
|
212
|
+
const filtered = filterBySeverity(result, minSeverity);
|
|
213
|
+
const decision = toDecisionResult(filtered, originalContent, config);
|
|
214
|
+
if (format === "json") {
|
|
215
|
+
console.log(JSON.stringify(buildDecisionJsonOutput(decision, label), null, 2));
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
printCliDecision(decision, label);
|
|
219
|
+
}
|
|
220
|
+
return { filtered, decision };
|
|
221
|
+
}
|
|
222
|
+
// --redact / --dry-run mode (supports --text, --file, --stdin)
|
|
223
|
+
if (redactMode) {
|
|
224
|
+
let inputText = null;
|
|
225
|
+
let label = "(inline text)";
|
|
226
|
+
if (textIdx !== -1 && args[textIdx + 1]) {
|
|
227
|
+
inputText = args[textIdx + 1];
|
|
228
|
+
}
|
|
229
|
+
else if (fileIdx !== -1 && args[fileIdx + 1]) {
|
|
230
|
+
const filePath = path.resolve(args[fileIdx + 1]);
|
|
231
|
+
if (!fs.existsSync(filePath)) {
|
|
232
|
+
console.error(chalk.red(t("cli.error_file_not_found", { path: filePath })));
|
|
233
|
+
process.exit(2);
|
|
234
|
+
}
|
|
235
|
+
inputText = readFileWithEncoding(filePath);
|
|
236
|
+
label = filePath;
|
|
237
|
+
}
|
|
238
|
+
else if (stdinMode || !process.stdin.isTTY) {
|
|
239
|
+
const chunks = [];
|
|
240
|
+
for await (const chunk of process.stdin)
|
|
241
|
+
chunks.push(chunk);
|
|
242
|
+
const raw = Buffer.concat(chunks);
|
|
243
|
+
// UTF-16 input is recognized by BOM; input without a BOM must be UTF-8.
|
|
244
|
+
inputText = (raw[0] === 0xff && raw[1] === 0xfe
|
|
245
|
+
? new TextDecoder("utf-16le").decode(raw)
|
|
246
|
+
: raw[0] === 0xef && raw[1] === 0xbb && raw[2] === 0xbf
|
|
247
|
+
? raw.toString("utf-8").slice(1)
|
|
248
|
+
: raw.toString("utf-8"))
|
|
249
|
+
.replace(/\r\n/g, "\n");
|
|
250
|
+
label = "(stdin)";
|
|
251
|
+
}
|
|
252
|
+
if (inputText === null) {
|
|
253
|
+
console.error(chalk.red(t("cli.error_redact_no_input")));
|
|
254
|
+
process.exit(2);
|
|
255
|
+
}
|
|
256
|
+
const result = redactText(inputText, config);
|
|
257
|
+
if (dryRun) {
|
|
258
|
+
// Dry-run: show preview only, do not output redacted text
|
|
259
|
+
console.error(chalk.bold(t("cli.dryrun_header", { count: result.total_findings, label })));
|
|
260
|
+
if (result.total_findings === 0) {
|
|
261
|
+
console.error(chalk.green(t("cli.dryrun_safe")));
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
for (const f of result.findings) {
|
|
265
|
+
const loc = f.line
|
|
266
|
+
? chalk.dim(t("cli.dryrun_location", { line: f.line, col: f.column ?? 0 }))
|
|
267
|
+
: "";
|
|
268
|
+
console.error(` ${chalk.yellow(f.type)}${loc} — ${f.description}`);
|
|
269
|
+
console.error(chalk.dim(t("cli.dryrun_preview", { preview: f.preview, type: f.type })));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
process.exit(result.total_findings > 0 ? 1 : 0);
|
|
273
|
+
}
|
|
274
|
+
const verified = redactAndVerify(inputText, config);
|
|
275
|
+
if (!verified.verified) {
|
|
276
|
+
if (format === "json") {
|
|
277
|
+
console.log(JSON.stringify({
|
|
278
|
+
label,
|
|
279
|
+
verified: false,
|
|
280
|
+
totalFindings: verified.totalFindings,
|
|
281
|
+
residualFindings: verified.residualFindings,
|
|
282
|
+
truncated: verified.wasTruncated,
|
|
283
|
+
summary: verified.summary,
|
|
284
|
+
}, null, 2));
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
console.error(chalk.red(t("cli.redact_incomplete", { residual: verified.residualFindings })));
|
|
288
|
+
}
|
|
289
|
+
process.exit(1);
|
|
290
|
+
}
|
|
291
|
+
if (format === "json") {
|
|
292
|
+
console.log(JSON.stringify({
|
|
293
|
+
label,
|
|
294
|
+
verified: true,
|
|
295
|
+
...sanitizeRedactResultForExport(result),
|
|
296
|
+
}, null, 2));
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
299
|
+
const outPath = outIdx !== -1 ? args[outIdx + 1] : undefined;
|
|
300
|
+
if (outPath) {
|
|
301
|
+
fs.writeFileSync(path.resolve(outPath), verified.redacted, "utf-8");
|
|
302
|
+
console.error(chalk.green(t("cli.redact_written", { path: path.resolve(outPath) })));
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
process.stdout.write(verified.redacted);
|
|
306
|
+
}
|
|
307
|
+
console.error(chalk.green("\n" + t("cli.redact_verified")));
|
|
308
|
+
console.error(chalk.dim(t("cli.redact_footer", { summary: verified.summary })));
|
|
309
|
+
}
|
|
310
|
+
process.exit(0);
|
|
311
|
+
}
|
|
312
|
+
// --dir 模式
|
|
313
|
+
if (dirIdx !== -1 && args[dirIdx + 1]) {
|
|
314
|
+
let dirPath;
|
|
315
|
+
try {
|
|
316
|
+
dirPath = validateCliScanPath(process.cwd(), args[dirIdx + 1], allowOutside);
|
|
317
|
+
}
|
|
318
|
+
catch (e) {
|
|
319
|
+
console.error(chalk.red(t("cli.error_path", { error: e instanceof Error ? e.message : String(e) })));
|
|
320
|
+
process.exit(2);
|
|
321
|
+
}
|
|
322
|
+
if (!fs.existsSync(dirPath)) {
|
|
323
|
+
console.error(chalk.red(t("cli.error_dir_not_found", { path: dirPath })));
|
|
324
|
+
process.exit(2);
|
|
325
|
+
}
|
|
326
|
+
const extensions = extIdx !== -1 ? args.slice(extIdx + 1).filter((a) => a.startsWith(".")) : undefined;
|
|
327
|
+
if (format === "text") {
|
|
328
|
+
console.log(chalk.bold(t("cli.scan_dir", { path: dirPath })));
|
|
329
|
+
if (extensions)
|
|
330
|
+
console.log(chalk.dim(t("cli.ext_filter", { exts: extensions.join(", ") })));
|
|
331
|
+
}
|
|
332
|
+
const files = collectFiles(dirPath, extensions, 200);
|
|
333
|
+
if (format === "text")
|
|
334
|
+
console.log(chalk.dim(t("cli.found_files", { count: files.length })));
|
|
335
|
+
const jsonResults = [];
|
|
336
|
+
let anyUnsafe = false;
|
|
337
|
+
let skippedFiles = 0;
|
|
338
|
+
const tasks = files.map((f) => async () => {
|
|
339
|
+
try {
|
|
340
|
+
const content = readFileWithEncoding(f);
|
|
341
|
+
return { file: f, content };
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
const readResults = await runWithConcurrency(tasks, SCAN_CONCURRENCY);
|
|
348
|
+
for (const item of readResults) {
|
|
349
|
+
if (!item) {
|
|
350
|
+
skippedFiles++;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const result = scanText(item.content, config);
|
|
354
|
+
const filtered = filterBySeverity(result, minSeverity);
|
|
355
|
+
if (!filtered.safe) {
|
|
356
|
+
anyUnsafe = true;
|
|
357
|
+
const decision = toDecisionResult(filtered, item.content, config);
|
|
358
|
+
if (format === "json") {
|
|
359
|
+
jsonResults.push({ file: item.file, ...buildDecisionJsonOutput(decision, item.file) });
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
printCliDecision(decision, item.file);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (skippedFiles > 0 && format === "text") {
|
|
367
|
+
console.log(chalk.dim(t("cli.skipped_files", { count: skippedFiles })));
|
|
368
|
+
}
|
|
369
|
+
if (format === "json") {
|
|
370
|
+
console.log(JSON.stringify({ dir: dirPath, scanned_files: files.length, skipped_files: skippedFiles, unsafe_files: jsonResults.length, results: jsonResults }, null, 2));
|
|
371
|
+
}
|
|
372
|
+
else if (!anyUnsafe) {
|
|
373
|
+
console.log(chalk.green(t("cli.dir_complete", { count: files.length })));
|
|
374
|
+
}
|
|
375
|
+
process.exit(anyUnsafe ? 1 : 0);
|
|
376
|
+
}
|
|
377
|
+
// --text mode
|
|
378
|
+
if (textIdx !== -1 && args[textIdx + 1]) {
|
|
379
|
+
const originalContent = args[textIdx + 1];
|
|
380
|
+
const result = scanText(originalContent, config);
|
|
381
|
+
const { decision } = output(result, t("cli.inline_label"), originalContent);
|
|
382
|
+
process.exit(decision.decision === "ALLOW" ? 0 : 1);
|
|
383
|
+
}
|
|
384
|
+
// --file mode
|
|
385
|
+
if (fileIdx !== -1 && args[fileIdx + 1]) {
|
|
386
|
+
let filePath;
|
|
387
|
+
try {
|
|
388
|
+
filePath = validateCliScanPath(process.cwd(), args[fileIdx + 1], allowOutside);
|
|
389
|
+
}
|
|
390
|
+
catch (e) {
|
|
391
|
+
console.error(chalk.red(t("cli.error_path", { error: e instanceof Error ? e.message : String(e) })));
|
|
392
|
+
process.exit(2);
|
|
393
|
+
}
|
|
394
|
+
if (!fs.existsSync(filePath)) {
|
|
395
|
+
console.error(chalk.red(t("cli.error_file_not_found", { path: filePath })));
|
|
396
|
+
process.exit(2);
|
|
397
|
+
}
|
|
398
|
+
const originalContent = readFileWithEncoding(filePath);
|
|
399
|
+
const result = scanText(originalContent, config);
|
|
400
|
+
const { decision } = output(result, filePath, originalContent);
|
|
401
|
+
process.exit(decision.decision === "ALLOW" ? 0 : 1);
|
|
402
|
+
}
|
|
403
|
+
// stdin 模式
|
|
404
|
+
if (stdinMode || !process.stdin.isTTY) {
|
|
405
|
+
const chunks = [];
|
|
406
|
+
for await (const chunk of process.stdin)
|
|
407
|
+
chunks.push(chunk);
|
|
408
|
+
const raw = Buffer.concat(chunks);
|
|
409
|
+
// UTF-16 input is recognized by BOM; input without a BOM must be UTF-8.
|
|
410
|
+
const originalContent = (raw[0] === 0xff && raw[1] === 0xfe
|
|
411
|
+
? new TextDecoder("utf-16le").decode(raw)
|
|
412
|
+
: raw[0] === 0xef && raw[1] === 0xbb && raw[2] === 0xbf
|
|
413
|
+
? raw.toString("utf-8").slice(1)
|
|
414
|
+
: raw.toString("utf-8"))
|
|
415
|
+
.replace(/\r\n/g, "\n");
|
|
416
|
+
const result = scanText(originalContent, config);
|
|
417
|
+
const { decision } = output(result, "(stdin)", originalContent);
|
|
418
|
+
process.exit(decision.decision === "ALLOW" ? 0 : 1);
|
|
419
|
+
}
|
|
420
|
+
// No input → show usage
|
|
421
|
+
console.log(chalk.bold(t("cli.usage_title")));
|
|
422
|
+
console.log(t("cli.usage_heading"));
|
|
423
|
+
console.log(t("cli.usage_text"));
|
|
424
|
+
console.log(t("cli.usage_file"));
|
|
425
|
+
console.log(t("cli.usage_dir"));
|
|
426
|
+
console.log(t("cli.usage_dir_ext"));
|
|
427
|
+
console.log(t("cli.usage_stdin"));
|
|
428
|
+
console.log(t("cli.usage_web"));
|
|
429
|
+
console.log("");
|
|
430
|
+
console.log(t("cli.usage_redact_heading"));
|
|
431
|
+
console.log(t("cli.usage_redact_text"));
|
|
432
|
+
console.log(t("cli.usage_redact_file"));
|
|
433
|
+
console.log(t("cli.usage_redact_out"));
|
|
434
|
+
console.log(t("cli.usage_redact_stdin"));
|
|
435
|
+
console.log(t("cli.usage_redact_dryrun"));
|
|
436
|
+
console.log("");
|
|
437
|
+
console.log(t("cli.usage_options_heading"));
|
|
438
|
+
console.log(t("cli.usage_opt_format"));
|
|
439
|
+
console.log(t("cli.usage_opt_severity"));
|
|
440
|
+
console.log(t("cli.usage_opt_redact"));
|
|
441
|
+
console.log(t("cli.usage_opt_dryrun"));
|
|
442
|
+
console.log(t("cli.usage_opt_out"));
|
|
443
|
+
console.log(t("cli.usage_opt_outside"));
|
|
444
|
+
console.log(t("cli.usage_opt_web"));
|
|
445
|
+
console.log(t("cli.usage_opt_port"));
|
|
446
|
+
console.log(t("cli.usage_opt_encoding"));
|
|
447
|
+
}
|