Spaces:
Sleeping
Sleeping
File size: 61,226 Bytes
da2e594 | 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 | /**
* Node-Specific Validators
*
* Provides detailed validation logic for commonly used n8n nodes.
* Each validator understands the specific requirements and patterns of its node.
*/
import { ValidationError, ValidationWarning } from './config-validator';
export interface NodeValidationContext {
config: Record<string, any>;
errors: ValidationError[];
warnings: ValidationWarning[];
suggestions: string[];
autofix: Record<string, any>;
}
export class NodeSpecificValidators {
/**
* Validate Slack node configuration with operation awareness
*/
static validateSlack(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const { resource, operation } = config;
// Message operations
if (resource === 'message') {
switch (operation) {
case 'send':
this.validateSlackSendMessage(context);
break;
case 'update':
this.validateSlackUpdateMessage(context);
break;
case 'delete':
this.validateSlackDeleteMessage(context);
break;
}
}
// Channel operations
else if (resource === 'channel') {
switch (operation) {
case 'create':
this.validateSlackCreateChannel(context);
break;
case 'get':
case 'getAll':
// These operations have minimal requirements
break;
}
}
// User operations
else if (resource === 'user') {
if (operation === 'get' && !config.user) {
errors.push({
type: 'missing_required',
property: 'user',
message: 'User identifier required - use email, user ID, or username',
fix: 'Set user to an email like "john@example.com" or user ID like "U1234567890"'
});
}
}
// Error handling for Slack operations
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Slack API can have rate limits and transient failures',
suggestion: 'Add onError: "continueRegularOutput" with retryOnFail for resilience'
});
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 2;
autofix.waitBetweenTries = 3000; // Slack rate limits
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput"'
});
}
}
private static validateSlackSendMessage(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
// Channel is required for sending messages
if (!config.channel && !config.channelId) {
errors.push({
type: 'missing_required',
property: 'channel',
message: 'Channel is required to send a message',
fix: 'Set channel to a channel name (e.g., "#general") or ID (e.g., "C1234567890")'
});
}
// Message content validation
if (!config.text && !config.blocks && !config.attachments) {
errors.push({
type: 'missing_required',
property: 'text',
message: 'Message content is required - provide text, blocks, or attachments',
fix: 'Add text field with your message content'
});
}
// Common patterns and suggestions
if (config.text && config.text.length > 40000) {
warnings.push({
type: 'inefficient',
property: 'text',
message: 'Message text exceeds Slack\'s 40,000 character limit',
suggestion: 'Split into multiple messages or use a file upload'
});
}
// Thread reply validation
if (config.replyToThread && !config.threadTs) {
warnings.push({
type: 'missing_common',
property: 'threadTs',
message: 'Thread timestamp required when replying to thread',
suggestion: 'Set threadTs to the timestamp of the thread parent message'
});
}
// Mention handling
if (config.text?.includes('@') && !config.linkNames) {
suggestions.push('Set linkNames=true to convert @mentions to user links');
autofix.linkNames = true;
}
}
private static validateSlackUpdateMessage(context: NodeValidationContext): void {
const { config, errors } = context;
if (!config.ts) {
errors.push({
type: 'missing_required',
property: 'ts',
message: 'Message timestamp (ts) is required to update a message',
fix: 'Provide the timestamp of the message to update'
});
}
if (!config.channel && !config.channelId) {
errors.push({
type: 'missing_required',
property: 'channel',
message: 'Channel is required to update a message',
fix: 'Provide the channel where the message exists'
});
}
}
private static validateSlackDeleteMessage(context: NodeValidationContext): void {
const { config, errors, warnings } = context;
if (!config.ts) {
errors.push({
type: 'missing_required',
property: 'ts',
message: 'Message timestamp (ts) is required to delete a message',
fix: 'Provide the timestamp of the message to delete'
});
}
if (!config.channel && !config.channelId) {
errors.push({
type: 'missing_required',
property: 'channel',
message: 'Channel is required to delete a message',
fix: 'Provide the channel where the message exists'
});
}
warnings.push({
type: 'security',
message: 'Message deletion is permanent and cannot be undone',
suggestion: 'Consider archiving or updating the message instead if you need to preserve history'
});
}
private static validateSlackCreateChannel(context: NodeValidationContext): void {
const { config, errors, warnings } = context;
if (!config.name) {
errors.push({
type: 'missing_required',
property: 'name',
message: 'Channel name is required',
fix: 'Provide a channel name (lowercase, no spaces, 1-80 characters)'
});
} else {
// Validate channel name format
const name = config.name;
if (name.includes(' ')) {
errors.push({
type: 'invalid_value',
property: 'name',
message: 'Channel names cannot contain spaces',
fix: 'Use hyphens or underscores instead of spaces'
});
}
if (name !== name.toLowerCase()) {
errors.push({
type: 'invalid_value',
property: 'name',
message: 'Channel names must be lowercase',
fix: 'Convert the channel name to lowercase'
});
}
if (name.length > 80) {
errors.push({
type: 'invalid_value',
property: 'name',
message: 'Channel name exceeds 80 character limit',
fix: 'Shorten the channel name'
});
}
}
}
/**
* Validate Google Sheets node configuration
*/
static validateGoogleSheets(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions } = context;
const { operation } = config;
// NOTE: Skip sheetId validation - it comes from credentials, not configuration
// In real workflows, sheetId is provided by Google Sheets credentials
// See Phase 3 validation results: 113/124 failures were false positives for this
// Operation-specific validations
switch (operation) {
case 'append':
this.validateGoogleSheetsAppend(context);
break;
case 'read':
this.validateGoogleSheetsRead(context);
break;
case 'update':
this.validateGoogleSheetsUpdate(context);
break;
case 'delete':
this.validateGoogleSheetsDelete(context);
break;
}
// Range format validation
if (config.range) {
this.validateGoogleSheetsRange(config.range, errors, warnings);
}
// FINAL STEP: Filter out sheetId errors (credential-provided field)
// Remove any sheetId validation errors that might have been added by nested validators
const filteredErrors: ValidationError[] = [];
for (const error of errors) {
// Skip sheetId errors - this field is provided by credentials
if (error.property === 'sheetId' && error.type === 'missing_required') {
continue;
}
// Skip errors about sheetId in nested paths (e.g., from resourceMapper validation)
if (error.property && error.property.includes('sheetId') && error.type === 'missing_required') {
continue;
}
filteredErrors.push(error);
}
// Replace errors array with filtered version
errors.length = 0;
errors.push(...filteredErrors);
}
private static validateGoogleSheetsAppend(context: NodeValidationContext): void {
const { config, errors, warnings, autofix } = context;
// In Google Sheets v4+, range is only required if NOT using the columns resourceMapper
// The columns parameter is a resourceMapper introduced in v4 that handles range automatically
if (!config.range && !config.columns) {
errors.push({
type: 'missing_required',
property: 'range',
message: 'Range or columns mapping is required for append operation',
fix: 'Specify range like "Sheet1!A:B" OR use columns with mappingMode'
});
}
// Check for common append settings
if (!config.options?.valueInputMode) {
warnings.push({
type: 'missing_common',
property: 'options.valueInputMode',
message: 'Consider setting valueInputMode for proper data formatting',
suggestion: 'Use "USER_ENTERED" to parse formulas and dates, or "RAW" for literal values'
});
autofix.options = { ...config.options, valueInputMode: 'USER_ENTERED' };
}
}
private static validateGoogleSheetsRead(context: NodeValidationContext): void {
const { config, errors, suggestions } = context;
if (!config.range) {
errors.push({
type: 'missing_required',
property: 'range',
message: 'Range is required for read operation',
fix: 'Specify range like "Sheet1!A:B" or "Sheet1!A1:B10"'
});
}
// Suggest data structure options
if (!config.options?.dataStructure) {
suggestions.push('Consider setting options.dataStructure to "object" for easier data manipulation');
}
}
private static validateGoogleSheetsUpdate(context: NodeValidationContext): void {
const { config, errors } = context;
if (!config.range) {
errors.push({
type: 'missing_required',
property: 'range',
message: 'Range is required for update operation',
fix: 'Specify the exact range to update like "Sheet1!A1:B10"'
});
}
if (!config.values && !config.rawData) {
errors.push({
type: 'missing_required',
property: 'values',
message: 'Values are required for update operation',
fix: 'Provide the data to write to the spreadsheet'
});
}
}
private static validateGoogleSheetsDelete(context: NodeValidationContext): void {
const { config, errors, warnings } = context;
if (!config.toDelete) {
errors.push({
type: 'missing_required',
property: 'toDelete',
message: 'Specify what to delete (rows or columns)',
fix: 'Set toDelete to "rows" or "columns"'
});
}
if (config.toDelete === 'rows' && !config.startIndex && config.startIndex !== 0) {
errors.push({
type: 'missing_required',
property: 'startIndex',
message: 'Start index is required when deleting rows',
fix: 'Specify the starting row index (0-based)'
});
}
warnings.push({
type: 'security',
message: 'Deletion is permanent. Consider backing up data first',
suggestion: 'Read the data before deletion to create a backup'
});
}
private static validateGoogleSheetsRange(
range: string,
errors: ValidationError[],
warnings: ValidationWarning[]
): void {
// Check basic format
if (!range.includes('!')) {
warnings.push({
type: 'inefficient',
property: 'range',
message: 'Range should include sheet name for clarity',
suggestion: 'Format: "SheetName!A1:B10" or "SheetName!A:B"'
});
}
// Check for common mistakes
if (range.includes(' ') && !range.match(/^'[^']+'/)) {
errors.push({
type: 'invalid_value',
property: 'range',
message: 'Sheet names with spaces must be quoted',
fix: 'Use single quotes around sheet name: \'Sheet Name\'!A1:B10'
});
}
// Validate A1 notation
const a1Pattern = /^('[^']+'|[^!]+)!([A-Z]+\d*:?[A-Z]*\d*|[A-Z]+:[A-Z]+|\d+:\d+)$/i;
if (!a1Pattern.test(range)) {
warnings.push({
type: 'inefficient',
property: 'range',
message: 'Range may not be in valid A1 notation',
suggestion: 'Examples: "Sheet1!A1:B10", "Sheet1!A:B", "Sheet1!1:10"'
});
}
}
/**
* Validate OpenAI node configuration
*/
static validateOpenAI(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const { resource, operation } = config;
if (resource === 'chat' && operation === 'create') {
// Model validation
if (!config.model) {
errors.push({
type: 'missing_required',
property: 'model',
message: 'Model selection is required',
fix: 'Choose a model like "gpt-4", "gpt-3.5-turbo", etc.'
});
} else {
// Check for deprecated models
const deprecatedModels = ['text-davinci-003', 'text-davinci-002'];
if (deprecatedModels.includes(config.model)) {
warnings.push({
type: 'deprecated',
property: 'model',
message: `Model ${config.model} is deprecated`,
suggestion: 'Use "gpt-3.5-turbo" or "gpt-4" instead'
});
}
}
// Message validation
if (!config.messages && !config.prompt) {
errors.push({
type: 'missing_required',
property: 'messages',
message: 'Messages or prompt required for chat completion',
fix: 'Add messages array or use the prompt field'
});
}
// Token limit warnings
if (config.maxTokens && config.maxTokens > 4000) {
warnings.push({
type: 'inefficient',
property: 'maxTokens',
message: 'High token limit may increase costs significantly',
suggestion: 'Consider if you really need more than 4000 tokens'
});
}
// Temperature validation
if (config.temperature !== undefined) {
if (config.temperature < 0 || config.temperature > 2) {
errors.push({
type: 'invalid_value',
property: 'temperature',
message: 'Temperature must be between 0 and 2',
fix: 'Set temperature between 0 (deterministic) and 2 (creative)'
});
}
}
}
// Error handling for AI API calls
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'AI APIs have rate limits and can return errors',
suggestion: 'Add onError: "continueRegularOutput" with retryOnFail and longer wait times'
});
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 3;
autofix.waitBetweenTries = 5000; // Longer wait for rate limits
autofix.alwaysOutputData = true;
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput"'
});
}
}
/**
* Validate MongoDB node configuration
*/
static validateMongoDB(context: NodeValidationContext): void {
const { config, errors, warnings, autofix } = context;
const { operation } = config;
// Collection is always required
if (!config.collection) {
errors.push({
type: 'missing_required',
property: 'collection',
message: 'Collection name is required',
fix: 'Specify the MongoDB collection to work with'
});
}
switch (operation) {
case 'find':
// Query validation
if (config.query) {
try {
JSON.parse(config.query);
} catch (e) {
errors.push({
type: 'invalid_value',
property: 'query',
message: 'Query must be valid JSON',
fix: 'Ensure query is valid JSON like: {"name": "John"}'
});
}
}
break;
case 'insert':
if (!config.fields && !config.documents) {
errors.push({
type: 'missing_required',
property: 'fields',
message: 'Document data is required for insert',
fix: 'Provide the data to insert'
});
}
break;
case 'update':
if (!config.query) {
warnings.push({
type: 'security',
message: 'Update without query will affect all documents',
suggestion: 'Add a query to target specific documents'
});
}
break;
case 'delete':
if (!config.query || config.query === '{}') {
errors.push({
type: 'invalid_value',
property: 'query',
message: 'Delete without query would remove all documents - this is a critical security issue',
fix: 'Add a query to specify which documents to delete'
});
}
break;
}
// Error handling for MongoDB operations
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
if (operation === 'find') {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'MongoDB queries can fail due to connection issues',
suggestion: 'Add onError: "continueRegularOutput" with retryOnFail'
});
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 3;
} else if (['insert', 'update', 'delete'].includes(operation)) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'MongoDB write operations should handle errors carefully',
suggestion: 'Add onError: "continueErrorOutput" to handle write failures separately'
});
autofix.onError = 'continueErrorOutput';
autofix.retryOnFail = true;
autofix.maxTries = 2;
autofix.waitBetweenTries = 1000;
}
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput" or "continueErrorOutput"'
});
}
}
/**
* Validate Postgres node configuration
*/
static validatePostgres(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const { operation } = config;
// Common query validation
if (['execute', 'select', 'insert', 'update', 'delete'].includes(operation)) {
this.validateSQLQuery(context, 'postgres');
}
// Operation-specific validation
switch (operation) {
case 'insert':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for insert operation',
fix: 'Specify the table to insert data into'
});
}
if (!config.columns && !config.dataMode) {
warnings.push({
type: 'missing_common',
property: 'columns',
message: 'No columns specified for insert',
suggestion: 'Define which columns to insert data into'
});
}
break;
case 'update':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for update operation',
fix: 'Specify the table to update'
});
}
if (!config.updateKey) {
warnings.push({
type: 'missing_common',
property: 'updateKey',
message: 'No update key specified',
suggestion: 'Set updateKey to identify which rows to update (e.g., "id")'
});
}
break;
case 'delete':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for delete operation',
fix: 'Specify the table to delete from'
});
}
if (!config.deleteKey) {
errors.push({
type: 'missing_required',
property: 'deleteKey',
message: 'Delete key is required to identify rows',
fix: 'Set deleteKey (e.g., "id") to specify which rows to delete'
});
}
break;
case 'execute':
if (!config.query) {
errors.push({
type: 'missing_required',
property: 'query',
message: 'SQL query is required',
fix: 'Provide the SQL query to execute'
});
}
break;
}
// Connection pool suggestions
if (config.connectionTimeout === undefined) {
suggestions.push('Consider setting connectionTimeout to handle slow connections');
}
// Error handling for database operations
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
if (operation === 'execute' && config.query?.toLowerCase().includes('select')) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Database reads can fail due to connection issues',
suggestion: 'Add onError: "continueRegularOutput" and retryOnFail: true'
});
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 3;
} else if (['insert', 'update', 'delete'].includes(operation)) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Database writes should handle errors carefully',
suggestion: 'Add onError: "stopWorkflow" with retryOnFail for transient failures'
});
autofix.onError = 'stopWorkflow';
autofix.retryOnFail = true;
autofix.maxTries = 2;
autofix.waitBetweenTries = 2000;
}
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput" or "stopWorkflow"'
});
}
}
/**
* Validate AI Agent node configuration
* Note: This provides basic model connection validation at the node level.
* Full AI workflow validation (tools, memory, etc.) is handled by workflow-validator.
*/
static validateAIAgent(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
// Check for language model configuration
// AI Agent nodes receive model connections via ai_languageModel connection type
// We validate this during workflow validation, but provide hints here for common issues
// Check prompt type configuration
if (config.promptType === 'define') {
if (!config.text || (typeof config.text === 'string' && config.text.trim() === '')) {
errors.push({
type: 'missing_required',
property: 'text',
message: 'Custom prompt text is required when promptType is "define"',
fix: 'Provide a custom prompt in the text field, or change promptType to "auto"'
});
}
}
// Check system message (RECOMMENDED)
if (!config.systemMessage || (typeof config.systemMessage === 'string' && config.systemMessage.trim() === '')) {
suggestions.push('AI Agent works best with a system message that defines the agent\'s role, capabilities, and constraints. Set systemMessage to provide context.');
} else if (typeof config.systemMessage === 'string' && config.systemMessage.trim().length < 20) {
warnings.push({
type: 'inefficient',
property: 'systemMessage',
message: 'System message is very short (< 20 characters)',
suggestion: 'Consider a more detailed system message to guide the agent\'s behavior'
});
}
// Check output parser configuration
if (config.hasOutputParser === true) {
warnings.push({
type: 'best_practice',
property: 'hasOutputParser',
message: 'Output parser is enabled. Ensure an ai_outputParser connection is configured in the workflow.',
suggestion: 'Connect an output parser node (e.g., Structured Output Parser) via ai_outputParser connection type'
});
}
// Check fallback model configuration
if (config.needsFallback === true) {
warnings.push({
type: 'best_practice',
property: 'needsFallback',
message: 'Fallback model is enabled. Ensure 2 language models are connected via ai_languageModel connections.',
suggestion: 'Connect a primary model and a fallback model to handle failures gracefully'
});
}
// Check maxIterations
if (config.maxIterations !== undefined) {
const maxIter = Number(config.maxIterations);
if (isNaN(maxIter) || maxIter < 1) {
errors.push({
type: 'invalid_value',
property: 'maxIterations',
message: 'maxIterations must be a positive number',
fix: 'Set maxIterations to a value >= 1 (e.g., 10)'
});
} else if (maxIter > 50) {
warnings.push({
type: 'inefficient',
property: 'maxIterations',
message: `maxIterations is set to ${maxIter}. High values can lead to long execution times and high costs.`,
suggestion: 'Consider reducing maxIterations to 10-20 for most use cases'
});
}
}
// Error handling for AI operations
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'AI models can fail due to API limits, rate limits, or invalid responses',
suggestion: 'Add onError: "continueRegularOutput" with retryOnFail for resilience'
});
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 2;
autofix.waitBetweenTries = 5000; // AI models may have rate limits
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput" or "stopWorkflow"'
});
}
}
/**
* Validate MySQL node configuration
*/
static validateMySQL(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions } = context;
const { operation } = config;
// MySQL uses similar validation to Postgres
if (['execute', 'insert', 'update', 'delete'].includes(operation)) {
this.validateSQLQuery(context, 'mysql');
}
// Operation-specific validation (similar to Postgres)
switch (operation) {
case 'insert':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for insert operation',
fix: 'Specify the table to insert data into'
});
}
break;
case 'update':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for update operation',
fix: 'Specify the table to update'
});
}
if (!config.updateKey) {
warnings.push({
type: 'missing_common',
property: 'updateKey',
message: 'No update key specified',
suggestion: 'Set updateKey to identify which rows to update'
});
}
break;
case 'delete':
if (!config.table) {
errors.push({
type: 'missing_required',
property: 'table',
message: 'Table name is required for delete operation',
fix: 'Specify the table to delete from'
});
}
break;
case 'execute':
if (!config.query) {
errors.push({
type: 'missing_required',
property: 'query',
message: 'SQL query is required',
fix: 'Provide the SQL query to execute'
});
}
break;
}
// MySQL-specific warnings
if (config.timezone === undefined) {
suggestions.push('Consider setting timezone to ensure consistent date/time handling');
}
// Error handling for MySQL operations (similar to Postgres)
if (!config.onError && !config.retryOnFail && !config.continueOnFail) {
if (operation === 'execute' && config.query?.toLowerCase().includes('select')) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Database queries can fail due to connection issues',
suggestion: 'Add onError: "continueRegularOutput" and retryOnFail: true'
});
} else if (['insert', 'update', 'delete'].includes(operation)) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Database modifications should handle errors carefully',
suggestion: 'Add onError: "stopWorkflow" with retryOnFail for transient failures'
});
}
}
}
/**
* Validate SQL queries for injection risks and common issues
*/
private static validateSQLQuery(
context: NodeValidationContext,
dbType: 'postgres' | 'mysql' | 'generic' = 'generic'
): void {
const { config, errors, warnings, suggestions } = context;
const query = config.query || config.deleteQuery || config.updateQuery || '';
if (!query) return;
const lowerQuery = query.toLowerCase();
// SQL injection checks
if (query.includes('${') || query.includes('{{')) {
warnings.push({
type: 'security',
message: 'Query contains template expressions that might be vulnerable to SQL injection',
suggestion: 'Use parameterized queries with query parameters instead of string interpolation'
});
suggestions.push('Example: Use "SELECT * FROM users WHERE id = $1" with queryParams: [userId]');
}
// DELETE without WHERE
if (lowerQuery.includes('delete') && !lowerQuery.includes('where')) {
errors.push({
type: 'invalid_value',
property: 'query',
message: 'DELETE query without WHERE clause will delete all records',
fix: 'Add a WHERE clause to specify which records to delete'
});
}
// UPDATE without WHERE
if (lowerQuery.includes('update') && !lowerQuery.includes('where')) {
warnings.push({
type: 'security',
message: 'UPDATE query without WHERE clause will update all records',
suggestion: 'Add a WHERE clause to specify which records to update'
});
}
// TRUNCATE warning
if (lowerQuery.includes('truncate')) {
warnings.push({
type: 'security',
message: 'TRUNCATE will remove all data from the table',
suggestion: 'Consider using DELETE with WHERE clause if you need to keep some data'
});
}
// DROP warning
if (lowerQuery.includes('drop')) {
errors.push({
type: 'invalid_value',
property: 'query',
message: 'DROP operations are extremely dangerous and will permanently delete database objects',
fix: 'Use this only if you really intend to delete tables/databases permanently'
});
}
// Performance suggestions
if (lowerQuery.includes('select *')) {
suggestions.push('Consider selecting specific columns instead of * for better performance');
}
// Database-specific checks
if (dbType === 'postgres') {
// PostgreSQL specific validations
if (query.includes('$$')) {
suggestions.push('Dollar-quoted strings detected - ensure they are properly closed');
}
} else if (dbType === 'mysql') {
// MySQL specific validations
if (query.includes('`')) {
suggestions.push('Using backticks for identifiers - ensure they are properly paired');
}
}
}
/**
* Validate HTTP Request node configuration with error handling awareness
*/
static validateHttpRequest(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const { method = 'GET', url, sendBody, authentication } = config;
// Basic URL validation
if (!url) {
errors.push({
type: 'missing_required',
property: 'url',
message: 'URL is required for HTTP requests',
fix: 'Provide the full URL including protocol (https://...)'
});
} else if (!url.startsWith('http://') && !url.startsWith('https://') && !url.includes('{{')) {
warnings.push({
type: 'invalid_value',
property: 'url',
message: 'URL should start with http:// or https://',
suggestion: 'Use https:// for secure connections'
});
}
// Method-specific validation
if (['POST', 'PUT', 'PATCH'].includes(method) && !sendBody) {
warnings.push({
type: 'missing_common',
property: 'sendBody',
message: `${method} requests typically include a body`,
suggestion: 'Set sendBody: true and configure the body content'
});
}
// Error handling recommendations
if (!config.retryOnFail && !config.onError && !config.continueOnFail) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'HTTP requests can fail due to network issues or server errors',
suggestion: 'Add onError: "continueRegularOutput" and retryOnFail: true for resilience'
});
// Auto-fix suggestion for error handling
autofix.onError = 'continueRegularOutput';
autofix.retryOnFail = true;
autofix.maxTries = 3;
autofix.waitBetweenTries = 1000;
}
// Check for deprecated continueOnFail
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput"'
});
autofix.onError = config.continueOnFail ? 'continueRegularOutput' : 'stopWorkflow';
delete autofix.continueOnFail;
}
// Check retry configuration
if (config.retryOnFail) {
// Validate retry settings
if (!['GET', 'HEAD', 'OPTIONS'].includes(method) && (!config.maxTries || config.maxTries > 3)) {
warnings.push({
type: 'best_practice',
property: 'maxTries',
message: `${method} requests might not be idempotent. Use fewer retries.`,
suggestion: 'Set maxTries: 2 for non-idempotent operations'
});
}
// Suggest alwaysOutputData for debugging
if (!config.alwaysOutputData) {
suggestions.push('Enable alwaysOutputData to capture error responses for debugging');
autofix.alwaysOutputData = true;
}
}
// Authentication warnings
if (url && url.includes('api') && !authentication) {
warnings.push({
type: 'security',
property: 'authentication',
message: 'API endpoints typically require authentication',
suggestion: 'Configure authentication method (Bearer token, API key, etc.)'
});
}
// Timeout recommendations
if (!config.timeout) {
suggestions.push('Consider setting a timeout to prevent hanging requests');
}
}
/**
* Validate Webhook node configuration with error handling
*/
static validateWebhook(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const { path, httpMethod = 'POST', responseMode } = config;
// Path validation
if (!path) {
errors.push({
type: 'missing_required',
property: 'path',
message: 'Webhook path is required',
fix: 'Provide a unique path like "my-webhook" or "github-events"'
});
} else if (path.startsWith('/')) {
warnings.push({
type: 'invalid_value',
property: 'path',
message: 'Webhook path should not start with /',
suggestion: 'Use "webhook-name" instead of "/webhook-name"'
});
}
// Error handling for webhooks
if (!config.onError && !config.continueOnFail) {
warnings.push({
type: 'best_practice',
property: 'onError',
message: 'Webhooks should always send a response, even on error',
suggestion: 'Set onError: "continueRegularOutput" to ensure webhook responses'
});
autofix.onError = 'continueRegularOutput';
}
// Check for deprecated continueOnFail in webhooks
if (config.continueOnFail !== undefined) {
warnings.push({
type: 'deprecated',
property: 'continueOnFail',
message: 'continueOnFail is deprecated. Use onError instead',
suggestion: 'Replace with onError: "continueRegularOutput"'
});
autofix.onError = 'continueRegularOutput';
delete autofix.continueOnFail;
}
// Note: responseNode mode validation moved to workflow-validator.ts
// where it has access to node-level onError property (not just config/parameters)
// Always output data for debugging
if (!config.alwaysOutputData) {
suggestions.push('Enable alwaysOutputData to debug webhook payloads');
autofix.alwaysOutputData = true;
}
// Security suggestions
suggestions.push('Consider adding webhook validation (HMAC signature verification)');
suggestions.push('Implement rate limiting for public webhooks');
}
/**
* Validate Code node configuration with n8n-specific patterns
*/
static validateCode(context: NodeValidationContext): void {
const { config, errors, warnings, suggestions, autofix } = context;
const language = config.language || 'javaScript';
const codeField = language === 'python' ? 'pythonCode' : 'jsCode';
const code = config[codeField] || '';
// Check for empty code
if (!code || code.trim() === '') {
errors.push({
type: 'missing_required',
property: codeField,
message: 'Code cannot be empty',
fix: 'Add your code logic. Start with: return [{json: {result: "success"}}]'
});
return;
}
// Language-specific validation
if (language === 'javaScript') {
this.validateJavaScriptCode(code, errors, warnings, suggestions);
} else if (language === 'python') {
this.validatePythonCode(code, errors, warnings, suggestions);
}
// Check return statement and format
this.validateReturnStatement(code, language, errors, warnings, suggestions);
// Check n8n variable usage
this.validateN8nVariables(code, language, warnings, suggestions, errors);
// Security and best practices
this.validateCodeSecurity(code, language, warnings);
// Error handling recommendations
if (!config.onError && code.length > 100) {
warnings.push({
type: 'best_practice',
property: 'errorHandling',
message: 'Code nodes can throw errors - consider error handling',
suggestion: 'Add onError: "continueRegularOutput" to handle errors gracefully'
});
autofix.onError = 'continueRegularOutput';
}
// Mode-specific suggestions
if (config.mode === 'runOnceForEachItem' && code.includes('items')) {
warnings.push({
type: 'best_practice',
message: 'In "Run Once for Each Item" mode, use $json instead of items array',
suggestion: 'Access current item data with $json.fieldName'
});
}
if (!config.mode && code.includes('$json')) {
warnings.push({
type: 'best_practice',
message: '$json only works in "Run Once for Each Item" mode',
suggestion: 'Either set mode: "runOnceForEachItem" or use items[0].json'
});
}
}
private static validateJavaScriptCode(
code: string,
errors: ValidationError[],
warnings: ValidationWarning[],
suggestions: string[]
): void {
// Check for syntax patterns that might fail
const syntaxPatterns = [
{ pattern: /const\s+const/, message: 'Duplicate const declaration' },
{ pattern: /let\s+let/, message: 'Duplicate let declaration' },
// Removed overly simplistic parenthesis check - it was causing false positives
// for valid patterns like $('NodeName').first().json or func()()
// { pattern: /\)\s*\)\s*{/, message: 'Extra closing parenthesis before {' },
// Only check for multiple closing braces at the very end (more likely to be an error)
{ pattern: /}\s*}\s*}\s*}$/, message: 'Multiple closing braces at end - check your nesting' }
];
syntaxPatterns.forEach(({ pattern, message }) => {
if (pattern.test(code)) {
errors.push({
type: 'invalid_value',
property: 'jsCode',
message: `Syntax error: ${message}`,
fix: 'Check your JavaScript syntax'
});
}
});
// Common async/await issues
// Check for await inside a non-async function (but top-level await is fine)
const functionWithAwait = /function\s+\w*\s*\([^)]*\)\s*{[^}]*await/;
const arrowWithAwait = /\([^)]*\)\s*=>\s*{[^}]*await/;
if ((functionWithAwait.test(code) || arrowWithAwait.test(code)) && !code.includes('async')) {
warnings.push({
type: 'best_practice',
message: 'Using await inside a non-async function',
suggestion: 'Add async keyword to the function, or use top-level await (Code nodes support it)'
});
}
// Check for common helper usage
if (code.includes('$helpers.httpRequest')) {
suggestions.push('$helpers.httpRequest is async - use: const response = await $helpers.httpRequest(...)');
}
if (code.includes('DateTime') && !code.includes('DateTime.')) {
warnings.push({
type: 'best_practice',
message: 'DateTime is from Luxon library',
suggestion: 'Use DateTime.now() or DateTime.fromISO() for date operations'
});
}
}
private static validatePythonCode(
code: string,
errors: ValidationError[],
warnings: ValidationWarning[],
suggestions: string[]
): void {
// Python-specific validation
const lines = code.split('\n');
// Check for tab/space mixing (already done in base validator)
// Check for common Python mistakes in n8n context
if (code.includes('__name__') && code.includes('__main__')) {
warnings.push({
type: 'inefficient',
message: 'if __name__ == "__main__" is not needed in Code nodes',
suggestion: 'Code node Python runs directly - remove the main check'
});
}
// Check for unavailable imports
const unavailableImports = [
{ module: 'requests', suggestion: 'Use JavaScript Code node with $helpers.httpRequest for HTTP requests' },
{ module: 'pandas', suggestion: 'Use built-in list/dict operations or JavaScript for data manipulation' },
{ module: 'numpy', suggestion: 'Use standard Python math operations' },
{ module: 'pip', suggestion: 'External packages cannot be installed in Code nodes' }
];
unavailableImports.forEach(({ module, suggestion }) => {
if (code.includes(`import ${module}`) || code.includes(`from ${module}`)) {
errors.push({
type: 'invalid_value',
property: 'pythonCode',
message: `Module '${module}' is not available in Code nodes`,
fix: suggestion
});
}
});
// Check indentation after colons
lines.forEach((line, i) => {
if (line.trim().endsWith(':') && i < lines.length - 1) {
const nextLine = lines[i + 1];
if (nextLine.trim() && !nextLine.startsWith(' ') && !nextLine.startsWith('\t')) {
errors.push({
type: 'invalid_value',
property: 'pythonCode',
message: `Missing indentation after line ${i + 1}`,
fix: 'Indent the line after the colon'
});
}
}
});
}
private static validateReturnStatement(
code: string,
language: string,
errors: ValidationError[],
warnings: ValidationWarning[],
suggestions: string[]
): void {
const hasReturn = /return\s+/.test(code);
if (!hasReturn) {
errors.push({
type: 'missing_required',
property: language === 'python' ? 'pythonCode' : 'jsCode',
message: 'Code must return data for the next node',
fix: language === 'python'
? 'Add: return [{"json": {"result": "success"}}]'
: 'Add: return [{json: {result: "success"}}]'
});
return;
}
// JavaScript return format validation
if (language === 'javaScript') {
// Check for object return without array
if (/return\s+{(?!.*\[).*}\s*;?$/s.test(code) && !code.includes('json:')) {
errors.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Return value must be an array of objects',
fix: 'Wrap in array: return [{json: yourObject}]'
});
}
// Check for primitive return
if (/return\s+(true|false|null|undefined|\d+|['"`])/m.test(code)) {
errors.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Cannot return primitive values directly',
fix: 'Return array of objects: return [{json: {value: yourData}}]'
});
}
// Check for array of non-objects
if (/return\s+\[[\s\n]*['"`\d]/.test(code)) {
errors.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Array items must be objects with json property',
fix: 'Use: return [{json: {value: "data"}}] not return ["data"]'
});
}
// Suggest proper return format for items
if (/return\s+items\s*;?$/.test(code) && !code.includes('map')) {
suggestions.push(
'Returning items directly is fine if they already have {json: ...} structure. ' +
'To modify: return items.map(item => ({json: {...item.json, newField: "value"}}))'
);
}
}
// Python return format validation
if (language === 'python') {
// Check for dict return without list
if (/return\s+{(?!.*\[).*}$/s.test(code)) {
errors.push({
type: 'invalid_value',
property: 'pythonCode',
message: 'Return value must be a list of dicts',
fix: 'Wrap in list: return [{"json": your_dict}]'
});
}
// Check for primitive return
if (/return\s+(True|False|None|\d+|['"`])/m.test(code)) {
errors.push({
type: 'invalid_value',
property: 'pythonCode',
message: 'Cannot return primitive values directly',
fix: 'Return list of dicts: return [{"json": {"value": your_data}}]'
});
}
}
}
private static validateN8nVariables(
code: string,
language: string,
warnings: ValidationWarning[],
suggestions: string[],
errors: ValidationError[]
): void {
// Check if code accesses input data
const inputPatterns = language === 'javaScript'
? ['items', '$input', '$json', '$node', '$prevNode']
: ['items', '_input'];
const usesInput = inputPatterns.some(pattern => code.includes(pattern));
if (!usesInput && code.length > 50) {
warnings.push({
type: 'missing_common',
message: 'Code doesn\'t reference input data',
suggestion: language === 'javaScript'
? 'Access input with: items, $input.all(), or $json (single-item mode)'
: 'Access input with: items variable'
});
}
// Check for expression syntax in Code nodes
if (code.includes('{{') && code.includes('}}')) {
errors.push({
type: 'invalid_value',
property: language === 'python' ? 'pythonCode' : 'jsCode',
message: 'Expression syntax {{...}} is not valid in Code nodes',
fix: 'Use regular JavaScript/Python syntax without double curly braces'
});
}
// Check for wrong $node syntax
if (code.includes('$node[')) {
warnings.push({
type: 'invalid_value',
property: language === 'python' ? 'pythonCode' : 'jsCode',
message: 'Use $(\'Node Name\') instead of $node[\'Node Name\'] in Code nodes',
suggestion: 'Replace $node[\'NodeName\'] with $(\'NodeName\')'
});
}
// Check for expression-only functions
const expressionOnlyFunctions = ['$now()', '$today()', '$tomorrow()', '.unique()', '.pluck(', '.keys()', '.hash('];
expressionOnlyFunctions.forEach(func => {
if (code.includes(func)) {
warnings.push({
type: 'invalid_value',
property: language === 'python' ? 'pythonCode' : 'jsCode',
message: `${func} is an expression-only function not available in Code nodes`,
suggestion: 'See Code node documentation for alternatives'
});
}
});
// Check for common variable mistakes
if (language === 'javaScript') {
// Using $ without proper variable
if (/\$(?![a-zA-Z])/.test(code) && !code.includes('${')) {
warnings.push({
type: 'best_practice',
message: 'Invalid $ usage detected',
suggestion: 'n8n variables start with $: $json, $input, $node, $workflow, $execution'
});
}
// Check for helpers usage
if (code.includes('helpers.') && !code.includes('$helpers')) {
warnings.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Use $helpers not helpers',
suggestion: 'Change helpers. to $helpers.'
});
}
// Check for $helpers usage without availability check
if (code.includes('$helpers') && !code.includes('typeof $helpers')) {
warnings.push({
type: 'best_practice',
message: '$helpers availability varies by n8n version',
suggestion: 'Check availability first: if (typeof $helpers !== "undefined" && $helpers.httpRequest) { ... }'
});
}
// Suggest available helpers
if (code.includes('$helpers')) {
suggestions.push(
'Common $helpers methods: httpRequest(), prepareBinaryData(). Note: getWorkflowStaticData is a standalone function - use $getWorkflowStaticData() instead'
);
}
// Check for incorrect getWorkflowStaticData usage
if (code.includes('$helpers.getWorkflowStaticData')) {
errors.push({
type: 'invalid_value',
property: 'jsCode',
message: '$helpers.getWorkflowStaticData() will cause "$helpers is not defined" error',
fix: 'Use $getWorkflowStaticData("global") or $getWorkflowStaticData("node") directly'
});
}
// Check for wrong JMESPath parameter order
if (code.includes('$jmespath(') && /\$jmespath\s*\(\s*['"`]/.test(code)) {
warnings.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Code node $jmespath has reversed parameter order: $jmespath(data, query)',
suggestion: 'Use: $jmespath(dataObject, "query.path") not $jmespath("query.path", dataObject)'
});
}
// Check for webhook data access patterns
if (code.includes('items[0].json') && !code.includes('.json.body')) {
// Check if previous node reference suggests webhook
if (code.includes('Webhook') || code.includes('webhook') ||
code.includes('$("Webhook")') || code.includes("$('Webhook')")) {
warnings.push({
type: 'invalid_value',
property: 'jsCode',
message: 'Webhook data is nested under .body property',
suggestion: 'Use items[0].json.body.fieldName instead of items[0].json.fieldName for webhook data'
});
}
// Also check for common webhook field names that suggest webhook data
else if (/items\[0\]\.json\.(payload|data|command|action|event|message)\b/.test(code)) {
warnings.push({
type: 'best_practice',
message: 'If processing webhook data, remember it\'s nested under .body',
suggestion: 'Webhook payloads are at items[0].json.body, not items[0].json'
});
}
}
}
// Check for JMESPath filters with unquoted numeric literals (both JS and Python)
const jmespathFunction = language === 'javaScript' ? '$jmespath' : '_jmespath';
if (code.includes(jmespathFunction + '(')) {
// Look for filter expressions with comparison operators and numbers
const filterPattern = /\[?\?[^[\]]*(?:>=?|<=?|==|!=)\s*(\d+(?:\.\d+)?)\s*\]/g;
let match;
while ((match = filterPattern.exec(code)) !== null) {
const number = match[1];
// Check if the number is NOT wrapped in backticks
const beforeNumber = code.substring(match.index, match.index + match[0].indexOf(number));
const afterNumber = code.substring(match.index + match[0].indexOf(number) + number.length);
if (!beforeNumber.includes('`') || !afterNumber.startsWith('`')) {
errors.push({
type: 'invalid_value',
property: language === 'python' ? 'pythonCode' : 'jsCode',
message: `JMESPath numeric literal ${number} must be wrapped in backticks`,
fix: `Change [?field >= ${number}] to [?field >= \`${number}\`]`
});
}
}
// Also provide a general suggestion if JMESPath is used
suggestions.push(
'JMESPath in n8n requires backticks around numeric literals in filters: [?age >= `18`]'
);
}
}
private static validateCodeSecurity(
code: string,
language: string,
warnings: ValidationWarning[]
): void {
// Security checks
const dangerousPatterns = [
{ pattern: /eval\s*\(/, message: 'Avoid eval() - it\'s a security risk' },
{ pattern: /Function\s*\(/, message: 'Avoid Function constructor - use regular functions' },
{ pattern: language === 'python' ? /exec\s*\(/ : /exec\s*\(/, message: 'Avoid exec() - it\'s a security risk' },
{ pattern: /process\.env/, message: 'Limited environment access in Code nodes' },
{ pattern: /import\s+\*/, message: 'Avoid import * - be specific about imports' }
];
dangerousPatterns.forEach(({ pattern, message }) => {
if (pattern.test(code)) {
warnings.push({
type: 'security',
message,
suggestion: 'Use safer alternatives or built-in functions'
});
}
});
// Special handling for require() - it's allowed for built-in modules
if (code.includes('require(')) {
// Check if it's requiring a built-in module
const builtinModules = ['crypto', 'util', 'querystring', 'url', 'buffer'];
const requirePattern = /require\s*\(\s*['"`](\w+)['"`]\s*\)/g;
let match;
while ((match = requirePattern.exec(code)) !== null) {
const moduleName = match[1];
if (!builtinModules.includes(moduleName)) {
warnings.push({
type: 'security',
message: `Cannot require('${moduleName}') - only built-in Node.js modules are available`,
suggestion: `Available modules: ${builtinModules.join(', ')}`
});
}
}
// If require is used without quotes, it might be dynamic
if (/require\s*\([^'"`]/.test(code)) {
warnings.push({
type: 'security',
message: 'Dynamic require() not supported',
suggestion: 'Use static require with string literals: require("crypto")'
});
}
}
// Check for crypto usage without require
if ((code.includes('crypto.') || code.includes('randomBytes') || code.includes('randomUUID')) &&
!code.includes('require') && language === 'javaScript') {
warnings.push({
type: 'invalid_value',
message: 'Using crypto without require statement',
suggestion: 'Add: const crypto = require("crypto"); at the beginning (ignore editor warnings)'
});
}
// File system access warning
if (/\b(fs|path|child_process)\b/.test(code)) {
warnings.push({
type: 'security',
message: 'File system and process access not available in Code nodes',
suggestion: 'Use other n8n nodes for file operations (e.g., Read/Write Files node)'
});
}
}
/**
* Validate Set node configuration
*/
static validateSet(context: NodeValidationContext): void {
const { config, errors, warnings } = context;
// Validate jsonOutput when present (used in JSON mode or when directly setting JSON)
if (config.jsonOutput !== undefined && config.jsonOutput !== null && config.jsonOutput !== '') {
try {
const parsed = JSON.parse(config.jsonOutput);
// Set node with JSON input expects an OBJECT {}, not an ARRAY []
// This is a common mistake that n8n UI catches but our validator should too
if (Array.isArray(parsed)) {
errors.push({
type: 'invalid_value',
property: 'jsonOutput',
message: 'Set node expects a JSON object {}, not an array []',
fix: 'Either wrap array items as object properties: {"items": [...]}, OR use a different approach for multiple items'
});
}
// Warn about empty objects
if (typeof parsed === 'object' && !Array.isArray(parsed) && Object.keys(parsed).length === 0) {
warnings.push({
type: 'inefficient',
property: 'jsonOutput',
message: 'jsonOutput is an empty object - this node will output no data',
suggestion: 'Add properties to the object or remove this node if not needed'
});
}
} catch (e) {
errors.push({
type: 'syntax_error',
property: 'jsonOutput',
message: `Invalid JSON in jsonOutput: ${e instanceof Error ? e.message : 'Syntax error'}`,
fix: 'Ensure jsonOutput contains valid JSON syntax'
});
}
}
// Validate mode-specific requirements
if (config.mode === 'manual') {
// In manual mode, at least one field should be defined
const hasFields = config.values && Object.keys(config.values).length > 0;
if (!hasFields && !config.jsonOutput) {
warnings.push({
type: 'missing_common',
message: 'Set node has no fields configured - will output empty items',
suggestion: 'Add fields in the Values section or use JSON mode'
});
}
}
}
} |