@kaynooo/cli-guard 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +277 -67
- package/package.json +8 -8
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
|
|
6
6
|
import { homedir as homedir4 } from "os";
|
|
7
7
|
import { dirname as dirname5 } from "path";
|
|
8
|
-
import
|
|
8
|
+
import process17 from "process";
|
|
9
9
|
// ../kit/src/args.ts
|
|
10
10
|
import process9 from "process";
|
|
11
11
|
import { parseArgs } from "util";
|
|
@@ -344,6 +344,23 @@ var STATUS_WORDS = {
|
|
|
344
344
|
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
345
345
|
|
|
346
346
|
// ../kit/src/format.ts
|
|
347
|
+
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
348
|
+
function formatSeconds(total) {
|
|
349
|
+
let rest = Math.max(0, Math.round(total));
|
|
350
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
351
|
+
const amount = Math.floor(rest / size);
|
|
352
|
+
rest -= amount * size;
|
|
353
|
+
return `${amount}${unit}`;
|
|
354
|
+
});
|
|
355
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
356
|
+
if (first === -1)
|
|
357
|
+
return "0s";
|
|
358
|
+
const next = amounts[first + 1];
|
|
359
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
360
|
+
}
|
|
361
|
+
function formatDuration(ms) {
|
|
362
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
363
|
+
}
|
|
347
364
|
function upTo(text, separator) {
|
|
348
365
|
const end = text.indexOf(separator);
|
|
349
366
|
return end === -1 ? text : text.slice(0, end);
|
|
@@ -352,24 +369,20 @@ var ESCAPE = String.fromCharCode(27);
|
|
|
352
369
|
|
|
353
370
|
// ../kit/src/help.ts
|
|
354
371
|
import process7 from "process";
|
|
355
|
-
var OPTIONAL =
|
|
372
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
356
373
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
357
374
|
var FULL_STOP = /\.$/;
|
|
358
375
|
function usageLine(usage, colors = paint(process7.stdout)) {
|
|
359
376
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
360
377
|
}
|
|
361
|
-
function helpText(usage, options, colors = paint(process7.stdout), { examples = [],
|
|
362
|
-
return [usageLine(usage, colors),
|
|
378
|
+
function helpText(usage, options, colors = paint(process7.stdout), { examples = [], exits = [] } = {}) {
|
|
379
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
363
380
|
`);
|
|
364
381
|
}
|
|
365
382
|
function exitRows(exits, colors = paint(process7.stdout)) {
|
|
366
383
|
if (exits.length === 0)
|
|
367
384
|
return [];
|
|
368
|
-
|
|
369
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
370
|
-
}
|
|
371
|
-
function replacesRows(replaces, colors = paint(process7.stdout)) {
|
|
372
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
385
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
373
386
|
}
|
|
374
387
|
function wantsHelpJson(env = process7.env) {
|
|
375
388
|
return env.KIT_HELP === "json";
|
|
@@ -395,29 +408,40 @@ function exampleRows(examples, colors = paint(process7.stdout)) {
|
|
|
395
408
|
return [];
|
|
396
409
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
397
410
|
}
|
|
411
|
+
var MAX_INLINE_CHOICES = 24;
|
|
398
412
|
function optionRows(options, colors = paint(process7.stdout)) {
|
|
399
413
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
400
414
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
401
|
-
const
|
|
415
|
+
const choices = option.choices?.join("|");
|
|
416
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
417
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
402
418
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
403
419
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
404
|
-
|
|
420
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
421
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
405
422
|
});
|
|
406
423
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
407
424
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
408
425
|
}
|
|
409
426
|
|
|
410
427
|
// ../kit/src/text.ts
|
|
411
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
412
428
|
function distance(a, b) {
|
|
413
|
-
|
|
414
|
-
|
|
429
|
+
const left = [...a];
|
|
430
|
+
const right = [...b];
|
|
431
|
+
let before = [];
|
|
432
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
433
|
+
for (const [i, x] of left.entries()) {
|
|
415
434
|
const current = [i + 1];
|
|
416
|
-
for (const [j,
|
|
417
|
-
|
|
435
|
+
for (const [j, y] of right.entries()) {
|
|
436
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
437
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
438
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
439
|
+
current.push(cost);
|
|
440
|
+
}
|
|
441
|
+
before = previous;
|
|
418
442
|
previous = current;
|
|
419
443
|
}
|
|
420
|
-
return previous[
|
|
444
|
+
return previous[right.length] ?? 0;
|
|
421
445
|
}
|
|
422
446
|
function closest(name, names) {
|
|
423
447
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -779,13 +803,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
|
779
803
|
// ../kit/src/cli.ts
|
|
780
804
|
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
781
805
|
import { dirname as dirname3, join as join5 } from "path";
|
|
782
|
-
import
|
|
806
|
+
import process14 from "process";
|
|
807
|
+
|
|
808
|
+
// ../kit/src/notify.ts
|
|
809
|
+
import process12 from "process";
|
|
810
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
811
|
+
var CANCELLED = 130;
|
|
812
|
+
function base64(text) {
|
|
813
|
+
return Buffer.from(text).toString("base64");
|
|
814
|
+
}
|
|
815
|
+
function notification(title, body, env = process12.env) {
|
|
816
|
+
const id = `kit${process12.pid}`;
|
|
817
|
+
const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
|
|
818
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
819
|
+
}
|
|
820
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
821
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
822
|
+
return;
|
|
823
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
824
|
+
}
|
|
783
825
|
|
|
784
826
|
// ../kit/src/usage.ts
|
|
785
827
|
import { appendFileSync, mkdirSync } from "fs";
|
|
786
828
|
import { homedir as homedir3 } from "os";
|
|
787
829
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
788
|
-
import
|
|
830
|
+
import process13 from "process";
|
|
789
831
|
|
|
790
832
|
// ../kit/src/logs.ts
|
|
791
833
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -799,14 +841,14 @@ var usageError;
|
|
|
799
841
|
function noteUsageError(message) {
|
|
800
842
|
usageError = message;
|
|
801
843
|
}
|
|
802
|
-
function stateHome(env =
|
|
844
|
+
function stateHome(env = process13.env) {
|
|
803
845
|
const dir = env.XDG_STATE_HOME;
|
|
804
846
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
805
847
|
}
|
|
806
|
-
function usagePath(env =
|
|
848
|
+
function usagePath(env = process13.env) {
|
|
807
849
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
808
850
|
}
|
|
809
|
-
function usageRecorded(env =
|
|
851
|
+
function usageRecorded(env = process13.env) {
|
|
810
852
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
811
853
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
812
854
|
}
|
|
@@ -820,7 +862,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
820
862
|
usageError = undefined;
|
|
821
863
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
822
864
|
}
|
|
823
|
-
function recordUsage(entry, env =
|
|
865
|
+
function recordUsage(entry, env = process13.env) {
|
|
824
866
|
if (!usageRecorded(env))
|
|
825
867
|
return;
|
|
826
868
|
try {
|
|
@@ -897,7 +939,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
897
939
|
header(colors, summary),
|
|
898
940
|
"",
|
|
899
941
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
900
|
-
...replacesRows(replaces, colors),
|
|
901
942
|
"",
|
|
902
943
|
...await commandRows(commands, colors),
|
|
903
944
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -911,8 +952,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
911
952
|
`);
|
|
912
953
|
}
|
|
913
954
|
function printError(prefix, message, hint, cause) {
|
|
914
|
-
const colors = paint(
|
|
915
|
-
const styled = takesControlCodes(
|
|
955
|
+
const colors = paint(process14.stderr);
|
|
956
|
+
const styled = takesControlCodes(process14.stderr);
|
|
916
957
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
917
958
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
918
959
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -955,11 +996,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
955
996
|
}
|
|
956
997
|
}
|
|
957
998
|
if (name === undefined && level.path.length > 1) {
|
|
958
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
999
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
959
1000
|
return 2;
|
|
960
1001
|
}
|
|
961
1002
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
962
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1003
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
963
1004
|
return 0;
|
|
964
1005
|
}
|
|
965
1006
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1094,10 +1135,13 @@ async function runCli(cli, argv = scriptArgs()) {
|
|
|
1094
1135
|
const version = cli.version ?? packageVersion();
|
|
1095
1136
|
if (argv[0] === COMPLETE)
|
|
1096
1137
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1138
|
+
const started = performance.now();
|
|
1097
1139
|
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1140
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1141
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1098
1142
|
if (cli.usage !== false) {
|
|
1099
1143
|
try {
|
|
1100
|
-
recordUsage(usageEntry(cli.name,
|
|
1144
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1101
1145
|
} catch {}
|
|
1102
1146
|
}
|
|
1103
1147
|
return code;
|
|
@@ -1157,6 +1201,7 @@ var ANSI_ESCAPES = { n: `
|
|
|
1157
1201
|
var ANSI_DIGITS = { x: 2, u: 4, U: 8 };
|
|
1158
1202
|
var OCTAL = /^[0-7]{1,3}/;
|
|
1159
1203
|
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1204
|
+
var INPUT_REDIRECT = /^\d*<(?![<&(>])/;
|
|
1160
1205
|
var MAX_DEPTH = 8;
|
|
1161
1206
|
var MAX_BRACES = 256;
|
|
1162
1207
|
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
@@ -1584,6 +1629,8 @@ function parseCommand(text) {
|
|
|
1584
1629
|
} else if (tokens.length > 1 && CASE_LABEL.test(first)) {
|
|
1585
1630
|
isWrapped = true;
|
|
1586
1631
|
tokens.shift();
|
|
1632
|
+
} else if (INPUT_REDIRECT.test(first)) {
|
|
1633
|
+
tokens.splice(0, first.replace(INPUT_REDIRECT, "") === "" ? 2 : 1);
|
|
1587
1634
|
} else if (spec !== undefined) {
|
|
1588
1635
|
isWrapped = true;
|
|
1589
1636
|
tokens.shift();
|
|
@@ -2188,6 +2235,52 @@ function printsTrackedEnv(program, args) {
|
|
|
2188
2235
|
return !rest.some((arg) => GIT_NO_PATCH.has(arg));
|
|
2189
2236
|
}
|
|
2190
2237
|
|
|
2238
|
+
// ../env/src/mask.ts
|
|
2239
|
+
var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
|
|
2240
|
+
var PLACEHOLDER = /^[$%{<(*/]/;
|
|
2241
|
+
function isPlaceholder(value) {
|
|
2242
|
+
return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
|
|
2243
|
+
}
|
|
2244
|
+
var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
|
|
2245
|
+
var WEAK_NAME = "token|credentials?|auth";
|
|
2246
|
+
var PLAIN_WORD = /^[a-z]+$/i;
|
|
2247
|
+
var AFTER_COLON = /:\s*$/;
|
|
2248
|
+
var DIGIT = /\d/;
|
|
2249
|
+
var KEY_VALUE_GAP = "\\s*[:=]\\s*";
|
|
2250
|
+
function isProse(value, before) {
|
|
2251
|
+
return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
|
|
2252
|
+
}
|
|
2253
|
+
function isWeak(value, before) {
|
|
2254
|
+
return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
|
|
2255
|
+
}
|
|
2256
|
+
function keyed(names, value) {
|
|
2257
|
+
return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
|
|
2258
|
+
}
|
|
2259
|
+
var TOKEN_FORMATS = [
|
|
2260
|
+
{ kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
|
|
2261
|
+
{ kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
|
|
2262
|
+
{ kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
|
|
2263
|
+
{ kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
|
|
2264
|
+
{ kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
|
|
2265
|
+
{ kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
|
|
2266
|
+
{ kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
|
|
2267
|
+
{ kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
|
|
2268
|
+
{ kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
|
|
2269
|
+
{ kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
|
|
2270
|
+
{ kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
|
|
2271
|
+
{ kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
|
|
2272
|
+
{ kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
|
|
2273
|
+
{ kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
|
|
2274
|
+
{ kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
|
|
2275
|
+
{ kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
|
|
2276
|
+
{ kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
|
|
2277
|
+
{ kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
|
|
2278
|
+
{ kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
|
|
2279
|
+
{ kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
|
|
2280
|
+
{ kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
|
|
2281
|
+
{ kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
|
|
2282
|
+
];
|
|
2283
|
+
|
|
2191
2284
|
// ../env/src/files.ts
|
|
2192
2285
|
var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
|
|
2193
2286
|
var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
|
|
@@ -2698,7 +2791,7 @@ function wrap(command) {
|
|
|
2698
2791
|
// ../pkg/src/added.ts
|
|
2699
2792
|
import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
|
|
2700
2793
|
import { dirname as dirname4, join as join6 } from "path";
|
|
2701
|
-
import
|
|
2794
|
+
import process16 from "process";
|
|
2702
2795
|
var REDIRECT2 = /^\d*[<>]/;
|
|
2703
2796
|
var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
|
|
2704
2797
|
var ADDS = {
|
|
@@ -2730,7 +2823,7 @@ function manifestName(folder) {
|
|
|
2730
2823
|
}
|
|
2731
2824
|
function ownPackages() {
|
|
2732
2825
|
const names = new Set;
|
|
2733
|
-
let folder =
|
|
2826
|
+
let folder = process16.cwd();
|
|
2734
2827
|
while (true) {
|
|
2735
2828
|
const name = manifestName(folder);
|
|
2736
2829
|
if (name !== undefined)
|
|
@@ -2835,7 +2928,7 @@ var OPTION_FLAGS = new Map([
|
|
|
2835
2928
|
]);
|
|
2836
2929
|
var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
|
|
2837
2930
|
var VALUE_FLAGS2 = new Set([...DIR_FLAGS, "--filter", "-F"]);
|
|
2838
|
-
var
|
|
2931
|
+
var PLAIN_WORD2 = /^[\w=@./:+-]+$/;
|
|
2839
2932
|
function actions(byAction) {
|
|
2840
2933
|
return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
|
|
2841
2934
|
}
|
|
@@ -2848,7 +2941,7 @@ function translate(from, to, subcommand, rest) {
|
|
|
2848
2941
|
const listed = ACTIONS[from].get(subcommand);
|
|
2849
2942
|
const action = listed === "install" && packages.length > 0 ? "add" : listed;
|
|
2850
2943
|
const command = action ? COMMANDS[to][action] : undefined;
|
|
2851
|
-
if (!action || command === undefined || !packages.every((name) =>
|
|
2944
|
+
if (!action || command === undefined || !packages.every((name) => PLAIN_WORD2.test(name)))
|
|
2852
2945
|
return null;
|
|
2853
2946
|
const options = [];
|
|
2854
2947
|
for (const flag of flags) {
|
|
@@ -2902,7 +2995,7 @@ function mismatchFor(request, pinned) {
|
|
|
2902
2995
|
return null;
|
|
2903
2996
|
const expected = [...pinned.managers];
|
|
2904
2997
|
const only = expected.length === 1 ? expected[0] : undefined;
|
|
2905
|
-
const canRewrite = only !== undefined && isRewritable && assignments.every((word) =>
|
|
2998
|
+
const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD2.test(word));
|
|
2906
2999
|
const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
|
|
2907
3000
|
const leading = piece.text.slice(0, piece.text.length - piece.text.trimStart().length);
|
|
2908
3001
|
const trailing = piece.text.slice(piece.text.trimEnd().length);
|
|
@@ -3181,6 +3274,10 @@ var FETCH_SUBSTITUTION = /(?:\$\(|<\(|`)\s*(?:curl|wget|fetch)\b/;
|
|
|
3181
3274
|
var RECURSIVE_LETTER = /r/i;
|
|
3182
3275
|
var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
|
|
3183
3276
|
var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
|
|
3277
|
+
var ABSOLUTE_HOME = /^(?:home\/[^/]+|root)\/([^/]+)$/;
|
|
3278
|
+
var EXEC_FLAGS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
3279
|
+
var REMOVER = /(?:^|\/)rm$/;
|
|
3280
|
+
var TRAILING_SLASH = /\/$/;
|
|
3184
3281
|
var SAFE_REBASE = new Set(["--abort", "--continue", "--quit", "--show-current-patch", "--skip", "--edit-todo"]);
|
|
3185
3282
|
var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
|
|
3186
3283
|
var VERSION_SUFFIX = /[\d.]+$/;
|
|
@@ -3196,6 +3293,10 @@ var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch hol
|
|
|
3196
3293
|
var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
|
|
3197
3294
|
var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
|
|
3198
3295
|
var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
|
|
3296
|
+
var PROTECTED_RM = "Never `rm -r` on a `.git` directory, on `~/Workspace` itself or on a dot-directory of the home (`~/.ssh`, `$HOME/.claude`, `~/.config`): it deletes a repository's whole history, every project, or the credentials and settings of the machine. Remove the named files inside, or ask the user to run it.";
|
|
3297
|
+
var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME`): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
|
|
3298
|
+
var REFLOG_EXPIRE = "Never `git reflog expire`, `git gc --prune=now` or `git update-ref -d`: they drop the reflog, unreachable commits or a ref, the only way back from a bad reset or rebase. Let git prune on its own schedule, and ask the user to run one when it is really wanted.";
|
|
3299
|
+
var DOCKER_PRUNE_ALL = "Never `docker system prune -a` (`--all`): it removes every image not used by a running container, volumes of other projects' stacks included with --volumes. `docker system prune` without -a drops only dangling data; remove named images with `docker rmi`.";
|
|
3199
3300
|
var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
|
|
3200
3301
|
function hasOption(args, long, shorts) {
|
|
3201
3302
|
for (const arg of args) {
|
|
@@ -3225,15 +3326,32 @@ function isBroadPath(path) {
|
|
|
3225
3326
|
return parts.length === 0;
|
|
3226
3327
|
return isAbsolute ? parts.length <= 1 : parts.every((part) => part === "..");
|
|
3227
3328
|
}
|
|
3228
|
-
function
|
|
3229
|
-
if (args.includes("--no-preserve-root"))
|
|
3230
|
-
return true;
|
|
3329
|
+
function recursiveTargets(args) {
|
|
3231
3330
|
const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
|
|
3232
3331
|
const isRecursive = options.some((arg) => arg === "--recursive" || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3332
|
+
return isRecursive ? args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--")) : [];
|
|
3333
|
+
}
|
|
3334
|
+
function isProtectedPath(path) {
|
|
3335
|
+
const home = HOME_PREFIX.exec(path);
|
|
3336
|
+
const parts = (home === null ? path : path.slice(home[0].length)).split("/").filter((part) => part !== "" && part !== ".");
|
|
3337
|
+
const last = parts.at(-1) ?? "";
|
|
3338
|
+
const absolute = path.startsWith("/") ? ABSOLUTE_HOME.exec(parts.join("/")) : null;
|
|
3339
|
+
const homeChild = parts.length === 1 ? last : undefined;
|
|
3340
|
+
const child = home === null ? absolute?.[1] : homeChild;
|
|
3341
|
+
return last === ".git" || child !== undefined && (child === "Workspace" || child.startsWith(".") && child !== "..");
|
|
3342
|
+
}
|
|
3343
|
+
function deletesFromHome(args) {
|
|
3344
|
+
const firstOption = args.findIndex((arg) => arg.startsWith("-") || arg === "(" || arg === "!");
|
|
3345
|
+
const starts = firstOption === -1 ? args : args.slice(0, firstOption);
|
|
3346
|
+
const deletes = args.includes("-delete") || args.some((arg, i) => EXEC_FLAGS.has(arg) && REMOVER.test(args[i + 1] ?? ""));
|
|
3347
|
+
return deletes && starts.some((start) => start === "/" || start.replace(TRAILING_SLASH, "") === HOME_PREFIX.exec(start)?.[0]);
|
|
3348
|
+
}
|
|
3349
|
+
function dockerPrunesAll(args) {
|
|
3350
|
+
const system = args.indexOf("system");
|
|
3351
|
+
return system !== -1 && args[system + 1] === "prune" && hasOption(args.slice(system + 2), ["--all"], "a");
|
|
3352
|
+
}
|
|
3353
|
+
function removesBroadly(args) {
|
|
3354
|
+
return args.includes("--no-preserve-root") || recursiveTargets(args).some(isBroadPath);
|
|
3237
3355
|
}
|
|
3238
3356
|
function checksOutTree(rest, operands) {
|
|
3239
3357
|
if (rest.includes("--"))
|
|
@@ -3264,6 +3382,12 @@ function gitDestructive(name, rest) {
|
|
|
3264
3382
|
}
|
|
3265
3383
|
if (name === "branch")
|
|
3266
3384
|
return hasOption(rest, [], "D") || hasOption(rest, ["--delete"], "d") && hasOption(rest, ["--force"], "f") ? BRANCH_DELETE : null;
|
|
3385
|
+
if (name === "reflog")
|
|
3386
|
+
return rest[0] === "expire" ? REFLOG_EXPIRE : null;
|
|
3387
|
+
if (name === "gc")
|
|
3388
|
+
return rest.some((arg) => arg === "--prune=now" || arg === "--prune=all") ? REFLOG_EXPIRE : null;
|
|
3389
|
+
if (name === "update-ref")
|
|
3390
|
+
return hasOption(rest, ["--delete"], "d") ? REFLOG_EXPIRE : null;
|
|
3267
3391
|
if (name === "rebase")
|
|
3268
3392
|
return rest.some((arg) => SAFE_REBASE.has(arg)) ? null : REBASE;
|
|
3269
3393
|
return name === "filter-branch" || name === "filter-repo" ? REWRITE_HISTORY : null;
|
|
@@ -3297,6 +3421,12 @@ function destructiveViolation(command) {
|
|
|
3297
3421
|
const { program, args } = parseCommand(piece.command);
|
|
3298
3422
|
if (program === "rm" && removesBroadly(args))
|
|
3299
3423
|
return BROAD_RM;
|
|
3424
|
+
if (program === "rm" && recursiveTargets(args).some(isProtectedPath))
|
|
3425
|
+
return PROTECTED_RM;
|
|
3426
|
+
if (program === "find" && deletesFromHome(args))
|
|
3427
|
+
return FIND_DELETE_HOME;
|
|
3428
|
+
if (program === "docker" && dockerPrunesAll(args))
|
|
3429
|
+
return DOCKER_PRUNE_ALL;
|
|
3300
3430
|
const git = gitCommandOf(program, args);
|
|
3301
3431
|
if (git === undefined)
|
|
3302
3432
|
continue;
|
|
@@ -3307,6 +3437,83 @@ function destructiveViolation(command) {
|
|
|
3307
3437
|
return null;
|
|
3308
3438
|
}
|
|
3309
3439
|
|
|
3440
|
+
// src/embedded.ts
|
|
3441
|
+
var PRINTERS3 = new Set(["echo", "printf"]);
|
|
3442
|
+
var ECHO_FLAGS = /^-[neE]+$/;
|
|
3443
|
+
var SHELL_STRING_FLAG = /^-[ABD-Z]*C[A-Z]*$/i;
|
|
3444
|
+
var PRINTF_SPEC = /%[sb]/g;
|
|
3445
|
+
var ESCAPE2 = /\\(.)/gs;
|
|
3446
|
+
var VERSION_SUFFIX2 = /[\d.]+$/;
|
|
3447
|
+
var CODE_FLAGS = new Map([["python", ["-c"]], ["perl", ["-e", "-E"]], ["ruby", ["-e"]], ["node", ["-e", "--eval", "-p", "--print"]], ["bun", ["-e", "--eval", "-p", "--print"]]]);
|
|
3448
|
+
var BACKTICK = String.fromCharCode(96);
|
|
3449
|
+
var QUOTED = String.raw`'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|${BACKTICK}(?:[^${BACKTICK}\\]|\\.)*${BACKTICK}`;
|
|
3450
|
+
var ARGV = new RegExp(String.raw`[[(]\s*((?:(?:${QUOTED})\s*,\s*)+(?:${QUOTED}))\s*(?:,\s*)?[\])]`, "gs");
|
|
3451
|
+
var LITERAL = new RegExp(QUOTED, "gs");
|
|
3452
|
+
var RUNS_SHELL = /(?:\b(?:system|exec\w*|spawn\w*|popen|run|call|check_\w+|Popen|getoutput|qx)|\$)\s*(?:\(\s*)?$/;
|
|
3453
|
+
var SHELL_BACKTICKS = new Set(["perl", "ruby"]);
|
|
3454
|
+
var ESCAPED = new Map([["n", `
|
|
3455
|
+
`], ["t", " "]]);
|
|
3456
|
+
function decode(text) {
|
|
3457
|
+
return text.replaceAll(ESCAPE2, (_, char) => ESCAPED.get(char) ?? char);
|
|
3458
|
+
}
|
|
3459
|
+
function literalValue(literal) {
|
|
3460
|
+
return decode(literal.slice(1, -1));
|
|
3461
|
+
}
|
|
3462
|
+
function printfText(args) {
|
|
3463
|
+
const [format = "", ...values] = args;
|
|
3464
|
+
const specs = format.match(PRINTF_SPEC)?.length ?? 0;
|
|
3465
|
+
if (specs === 0)
|
|
3466
|
+
return decode(format);
|
|
3467
|
+
let text = "";
|
|
3468
|
+
for (let rest = values;; rest = rest.slice(specs)) {
|
|
3469
|
+
let index = 0;
|
|
3470
|
+
text += format.replaceAll(PRINTF_SPEC, () => rest[index++] ?? "");
|
|
3471
|
+
if (rest.length <= specs)
|
|
3472
|
+
return decode(text);
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
function printed(command) {
|
|
3476
|
+
const { program, args } = parseCommand(command);
|
|
3477
|
+
if (!PRINTERS3.has(program))
|
|
3478
|
+
return null;
|
|
3479
|
+
if (program === "printf")
|
|
3480
|
+
return printfText(args[0] === "--" ? args.slice(1) : args);
|
|
3481
|
+
return args.filter((arg, index) => !(ECHO_FLAGS.test(arg) && args.slice(0, index).every((before) => ECHO_FLAGS.test(before)))).join(" ");
|
|
3482
|
+
}
|
|
3483
|
+
function readsStdin(args) {
|
|
3484
|
+
if (args.some((arg) => SHELL_STRING_FLAG.test(arg)))
|
|
3485
|
+
return false;
|
|
3486
|
+
return args.includes("-s") || args.includes("-") || args.every((arg) => arg.startsWith("-"));
|
|
3487
|
+
}
|
|
3488
|
+
function fedCommands(command) {
|
|
3489
|
+
const pieces = splitCommand(command);
|
|
3490
|
+
return pieces.flatMap((piece, index) => {
|
|
3491
|
+
const before = pieces[index - 1];
|
|
3492
|
+
const { program, args } = parseCommand(piece.command);
|
|
3493
|
+
if (!SHELLS.has(program) || before?.separator !== "|" || !readsStdin(args))
|
|
3494
|
+
return [];
|
|
3495
|
+
const text = printed(before.command);
|
|
3496
|
+
return text === null ? [] : text.split(`
|
|
3497
|
+
`).filter((line) => line.trim() !== "");
|
|
3498
|
+
});
|
|
3499
|
+
}
|
|
3500
|
+
function scriptedCommands(command) {
|
|
3501
|
+
return splitCommand(command).flatMap((piece) => {
|
|
3502
|
+
const { program, args } = parseCommand(piece.command);
|
|
3503
|
+
const language = program.replace(VERSION_SUFFIX2, "");
|
|
3504
|
+
const flags = CODE_FLAGS.get(language);
|
|
3505
|
+
const flag = flags === undefined ? -1 : args.findIndex((arg) => flags.includes(arg));
|
|
3506
|
+
const code = flag === -1 ? undefined : args[flag + 1];
|
|
3507
|
+
if (code === undefined)
|
|
3508
|
+
return [];
|
|
3509
|
+
const argvs = [...code.matchAll(ARGV)].map(([, list = ""]) => (list.match(LITERAL) ?? []).map(literalValue).join(" "));
|
|
3510
|
+
const runs = [...code.matchAll(LITERAL)].filter(({ 0: literal, index }) => RUNS_SHELL.test(code.slice(0, index)) || literal.startsWith("`") && SHELL_BACKTICKS.has(language));
|
|
3511
|
+
const lines = runs.flatMap(([literal]) => literalValue(literal).split(`
|
|
3512
|
+
`));
|
|
3513
|
+
return [...argvs, ...lines].filter((line) => line.trim() !== "");
|
|
3514
|
+
});
|
|
3515
|
+
}
|
|
3516
|
+
|
|
3310
3517
|
// src/remote.ts
|
|
3311
3518
|
var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
|
|
3312
3519
|
var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
|
|
@@ -3408,7 +3615,7 @@ var PYTHON_COUNT = /^\s*,\s*(\d+)\s*\)/;
|
|
|
3408
3615
|
var SPACE2 = /^\s*/;
|
|
3409
3616
|
var COMMA = /^\s*,\s*/;
|
|
3410
3617
|
var REGEX_FLAGS = /^[gm]*$/;
|
|
3411
|
-
var
|
|
3618
|
+
var PLAIN_WORD3 = /^[\w@%+=:,./*?-]+$/;
|
|
3412
3619
|
var SED_SEPARATORS = /^[\s;]*/;
|
|
3413
3620
|
var SED_SEPARATOR = /[\s;]/;
|
|
3414
3621
|
var BRE_ESCAPED = new Map([["(", "("], [")", ")"], ["{", "{"], ["}", "}"], ["+", "+"], ["?", "?"], ["|", "|"]]);
|
|
@@ -3671,7 +3878,7 @@ function sedPairs(script, isExtended) {
|
|
|
3671
3878
|
return pairs.length === 0 ? undefined : pairs;
|
|
3672
3879
|
}
|
|
3673
3880
|
function fileWord(path) {
|
|
3674
|
-
return
|
|
3881
|
+
return PLAIN_WORD3.test(path) ? path : shellQuote(path);
|
|
3675
3882
|
}
|
|
3676
3883
|
function flagsOf(pair) {
|
|
3677
3884
|
return [pair.regex === true ? " --regex" : "", pair.all === true ? " --all" : "", pair.count === undefined ? "" : ` -n ${pair.count}`].join("");
|
|
@@ -3794,7 +4001,9 @@ async function checkCommand(command, context) {
|
|
|
3794
4001
|
if (message !== null)
|
|
3795
4002
|
violations.push({ rule, message });
|
|
3796
4003
|
};
|
|
3797
|
-
const
|
|
4004
|
+
const shown = commandsRun(command);
|
|
4005
|
+
const run = [...shown, ...shown.flatMap(fedCommands).flatMap((each) => commandsRun(each))];
|
|
4006
|
+
const scripted = run.flatMap(scriptedCommands).flatMap((each) => commandsRun(each));
|
|
3798
4007
|
const first = (messages) => messages.find((message) => message !== null) ?? null;
|
|
3799
4008
|
const guarded = async (rule, check) => {
|
|
3800
4009
|
try {
|
|
@@ -3806,8 +4015,8 @@ async function checkCommand(command, context) {
|
|
|
3806
4015
|
};
|
|
3807
4016
|
const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
|
|
3808
4017
|
add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
|
|
3809
|
-
add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
|
|
3810
|
-
add("destructive", await guarded("destructive", () => first(run.map(destructiveViolation))));
|
|
4018
|
+
add("git", await guarded("git", () => first([...run, ...scripted].map((each) => gitViolation(each, context.isPushAsked)))));
|
|
4019
|
+
add("destructive", await guarded("destructive", () => first([...run, ...scripted].map(destructiveViolation))));
|
|
3811
4020
|
const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
|
|
3812
4021
|
add("commit", commit === null ? null : `${commit} ${USE_GC}`);
|
|
3813
4022
|
add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
|
|
@@ -3854,6 +4063,11 @@ var BINS = {
|
|
|
3854
4063
|
gc: "`gc <title> [-m <line>]... [--ticket <line>]... -- <path>...`: commits exactly those paths, refusing with nothing staged when the message breaks a commit rule, a path has no change or other files are already staged; use it instead of chaining git add, status and commit.",
|
|
3855
4064
|
gp: "`gp [--repos] [dir]...`: pushes the current branch when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
|
|
3856
4065
|
gb: "`gb [branch]`: switches to a branch, a remote one getting its tracking branch, `gb -c <name>` creating one; without a terminal it lists the branches (`--json`), with how each stands against its upstream and whether it is merged.",
|
|
4066
|
+
gf: "`gf [--repos] [dir]...`: fetches with prune and fast-forwards the branch onto its upstream, saying what came in; a diverged branch or a tree the fast-forward would overwrite is refused untouched, `--no-pull` fetches only; use it instead of `git pull` and a git fetch per nested repository.",
|
|
4067
|
+
gm: "`gm [branch]`: merges the branch into the current one, saying fast-forward or merge commit, the commits and the files that came in; a conflict lists every conflicted file with its conflict regions and exits 1, `--dry-run` tries the merge without touching the tree, `--continue`/`--abort`, `--squash`; with no branch it picks one, or lists each with its verdict off a terminal; use it instead of git merge then git diff and reading conflict markers.",
|
|
4068
|
+
gcl: "`gcl <repo> [dir]`: clones a URL, scp address or owner/name into the workspace folder and prints the path, an existing clone being fetched instead; use it instead of git clone with the folder typed out.",
|
|
4069
|
+
gd: "`gd [path]...`: the tracked changes per file with added and removed lines, staged apart from unstaged, the patch of the paths given, `--staged`, `--ref <rev>`; use it instead of `git diff --stat` then `git diff <path>`.",
|
|
4070
|
+
gu: "`gu <path>...`: discards the unstaged changes of the paths after saving them as a patch, `--staged` unstages, `--commit` undoes the last unpushed commit keeping its changes staged; use it instead of git restore and git reset.",
|
|
3857
4071
|
waitfor: "`waitfor --file <log> --until <regex> [--fail <regex>]`, `--port <n>`, `--url <url>`, `--pid <n>` (`-t 5m`): waits until the line shows, the port listens, the URL answers 2xx or the process exits, exits 1 on a --fail line with the lines around it, 2 on a timeout with the last lines; `waitfor task <id>` waits for a background Bash task and prints its exit code, last lines and failure lines; use it instead of sleep and tail, `until ! pgrep -f` or polling loops.",
|
|
3858
4072
|
slot: "`slot [-l <lock>] -- <cmd>`: waits for one of the machine-wide slots shared by every session (half the CPUs), then runs the command; `--lock <name>` also holds a named lock for what must not run twice (a shared test database), `slot ls` lists holders and waiters; run heavy jobs (phpunit, playwright, vue-tsc, a full test suite) through it instead of a flock wrapper.",
|
|
3859
4073
|
gl: "`gl ci [ref]` waits for the GitLab pipeline covering a commit and prints each failed job's tests (exit 0/1/2), `gl runs`, `gl logs <pipeline> [-j job] [--full]`; use it instead of `glab ci` or `glab api .../pipelines/<id>/jobs` polled in a sleep loop.",
|
|
@@ -3983,9 +4197,8 @@ var checkUsage = `guard check [options] [<command> | -]
|
|
|
3983
4197
|
|
|
3984
4198
|
Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), destructive commands (reset --hard, force push, rebase, broad rm), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
|
|
3985
4199
|
Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
|
|
3986
|
-
The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command
|
|
3987
|
-
|
|
3988
|
-
Exits 0 when the command is clean, 1 when a rule is broken, 2 on a usage error.`;
|
|
4200
|
+
The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.`;
|
|
4201
|
+
var CHECK_EXITS = [[0, "the command is clean"], [1, "a rule is broken"], [2, "a usage error"]];
|
|
3989
4202
|
var checkOptions = {
|
|
3990
4203
|
json: jsonOption("{violations, command, notes, packages} for a hook"),
|
|
3991
4204
|
cwd: { type: "string", description: "the directory the command runs in (default: here)" },
|
|
@@ -3994,9 +4207,8 @@ var checkOptions = {
|
|
|
3994
4207
|
};
|
|
3995
4208
|
var pathUsage = `guard path [--json] <path>...
|
|
3996
4209
|
|
|
3997
|
-
Checks the paths a file tool would read, edit or write: env files are refused
|
|
3998
|
-
|
|
3999
|
-
Exits 0 when every path is clean, 1 when one is refused, 2 on a usage error.`;
|
|
4210
|
+
Checks the paths a file tool would read, edit or write: env files are refused.`;
|
|
4211
|
+
var PATH_EXITS = [[0, "every path is clean"], [1, "one is refused"], [2, "a usage error"]];
|
|
4000
4212
|
var pathOptions = {
|
|
4001
4213
|
json: jsonOption("{violations} for a hook")
|
|
4002
4214
|
};
|
|
@@ -4004,9 +4216,8 @@ var hookUsage = `guard hook <${EVENTS.join("|")}>
|
|
|
4004
4216
|
|
|
4005
4217
|
Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
|
|
4006
4218
|
pre-tool-use refuses a Bash call breaking a rule, an install pkg refuses (or fails to check), and a file tool (Read, Edit, MultiEdit, Write, NotebookEdit, Grep, Glob) reaching an env file; user-prompt-submit remembers whether the prompt asked for a push; session-start lists the installed @kaynooo/cli-* bins.
|
|
4007
|
-
A failure exits 1, which Claude Code reports without blocking the call
|
|
4008
|
-
|
|
4009
|
-
Exits 0 when it answered, 1 on a failure or an unknown event (never 2, which would block the call).`;
|
|
4219
|
+
A failure exits 1, which Claude Code reports without blocking the call.`;
|
|
4220
|
+
var HOOK_EXITS = [[0, "it answered"], [1, "a failure or an unknown event (never 2, which would block the call)"]];
|
|
4010
4221
|
var MAX_READ = 1e6;
|
|
4011
4222
|
function readText(path) {
|
|
4012
4223
|
try {
|
|
@@ -4018,10 +4229,10 @@ function readText(path) {
|
|
|
4018
4229
|
}
|
|
4019
4230
|
function report2(violations) {
|
|
4020
4231
|
for (const { rule, message } of violations)
|
|
4021
|
-
console.log(`${role("problem",
|
|
4232
|
+
console.log(`${role("problem", process17.stdout)(rule)}: ${message}`);
|
|
4022
4233
|
}
|
|
4023
4234
|
async function check(args) {
|
|
4024
|
-
const parsed = parse(args, checkUsage, checkOptions);
|
|
4235
|
+
const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
|
|
4025
4236
|
const { values, positionals } = parsed;
|
|
4026
4237
|
if (positionals.length > 1)
|
|
4027
4238
|
fail(`give the command as one argument, quoted
|
|
@@ -4030,7 +4241,7 @@ ${checkUsage}`);
|
|
|
4030
4241
|
const given = positionals[0] ?? "-";
|
|
4031
4242
|
const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
|
|
4032
4243
|
const context = {
|
|
4033
|
-
cwd: values.cwd ??
|
|
4244
|
+
cwd: values.cwd ?? process17.cwd(),
|
|
4034
4245
|
home: homedir4(),
|
|
4035
4246
|
isPushAsked: values["push-asked"] === true,
|
|
4036
4247
|
canRewrite: true,
|
|
@@ -4045,12 +4256,12 @@ ${checkUsage}`);
|
|
|
4045
4256
|
else
|
|
4046
4257
|
report2(verdict.violations);
|
|
4047
4258
|
if (values.json !== true && verdict.command !== command)
|
|
4048
|
-
console.log(`${role("label",
|
|
4259
|
+
console.log(`${role("label", process17.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
|
|
4049
4260
|
${note}`).join("")}`);
|
|
4050
4261
|
return verdict.violations.length > 0 ? 1 : 0;
|
|
4051
4262
|
}
|
|
4052
4263
|
function path(args) {
|
|
4053
|
-
const parsed = parse(args, pathUsage, pathOptions);
|
|
4264
|
+
const parsed = parse(args, pathUsage, pathOptions, { exits: PATH_EXITS });
|
|
4054
4265
|
if (parsed.positionals.length === 0)
|
|
4055
4266
|
fail(`give at least one path
|
|
4056
4267
|
|
|
@@ -4064,20 +4275,19 @@ ${pathUsage}`);
|
|
|
4064
4275
|
}
|
|
4065
4276
|
var rulesUsage = `guard rules [--json]
|
|
4066
4277
|
|
|
4067
|
-
Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs
|
|
4068
|
-
|
|
4069
|
-
Exits 0 once it listed them.`;
|
|
4278
|
+
Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs.`;
|
|
4279
|
+
var RULES_EXITS = [[0, "it listed them"]];
|
|
4070
4280
|
var rulesOptions = {
|
|
4071
4281
|
json: jsonOption("[{name, refuses, route, runs}]")
|
|
4072
4282
|
};
|
|
4073
4283
|
function rules(args) {
|
|
4074
|
-
const parsed = parse(args, rulesUsage, rulesOptions);
|
|
4284
|
+
const parsed = parse(args, rulesUsage, rulesOptions, { exits: RULES_EXITS });
|
|
4075
4285
|
if (parsed.values.json === true) {
|
|
4076
4286
|
console.log(JSON.stringify(RULES2));
|
|
4077
4287
|
return 0;
|
|
4078
4288
|
}
|
|
4079
4289
|
for (const rule of RULES2)
|
|
4080
|
-
console.log(`${role("id",
|
|
4290
|
+
console.log(`${role("id", process17.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
|
|
4081
4291
|
${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
|
|
4082
4292
|
return 0;
|
|
4083
4293
|
}
|
|
@@ -4105,7 +4315,7 @@ function machine() {
|
|
|
4105
4315
|
};
|
|
4106
4316
|
}
|
|
4107
4317
|
async function hookCommand(args) {
|
|
4108
|
-
const parsed = parse(args, hookUsage, {});
|
|
4318
|
+
const parsed = parse(args, hookUsage, {}, { exits: HOOK_EXITS });
|
|
4109
4319
|
const event = parsed.positionals[0] ?? "";
|
|
4110
4320
|
if (!EVENTS.includes(event))
|
|
4111
4321
|
fail(`unknown event ${event}
|
|
@@ -4116,7 +4326,7 @@ ${hookUsage}`, 1);
|
|
|
4116
4326
|
console.log(JSON.stringify(reply));
|
|
4117
4327
|
return 0;
|
|
4118
4328
|
}
|
|
4119
|
-
|
|
4329
|
+
process17.exitCode = await runCli({
|
|
4120
4330
|
name: "guard",
|
|
4121
4331
|
usage: false,
|
|
4122
4332
|
about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-guard",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.13.0",
|
|
5
5
|
"description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -36,12 +36,12 @@
|
|
|
36
36
|
"guard": "$npm_execpath src/cli.ts"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@kaynooo/cli-db": "0.
|
|
40
|
-
"@kaynooo/cli-edit": "0.
|
|
41
|
-
"@kaynooo/cli-env": "0.13.
|
|
42
|
-
"@kaynooo/cli-git": "0.
|
|
43
|
-
"@kaynooo/cli-kit": "0.
|
|
44
|
-
"@kaynooo/cli-out": "0.14.
|
|
45
|
-
"@kaynooo/cli-pkg": "0.
|
|
39
|
+
"@kaynooo/cli-db": "0.13.0",
|
|
40
|
+
"@kaynooo/cli-edit": "0.11.0",
|
|
41
|
+
"@kaynooo/cli-env": "0.13.3",
|
|
42
|
+
"@kaynooo/cli-git": "0.16.0",
|
|
43
|
+
"@kaynooo/cli-kit": "0.39.0",
|
|
44
|
+
"@kaynooo/cli-out": "0.14.4",
|
|
45
|
+
"@kaynooo/cli-pkg": "0.15.2"
|
|
46
46
|
}
|
|
47
47
|
}
|